Database - Dynamic Initalisations of C++ Objects Based On User Input - Stack Overflow
Database - Dynamic Initalisations of C++ Objects Based On User Input - Stack Overflow
1 2 help
dynamicinitalisationsofc++objectsbasedonuserinput
HeysorryforthepreviousQuestion
OK..Myprojectistocreateandrunadatabaseforacollegeusingc++
IhavetouseUSNwhichisaUniqueStudentNumbertoaccessthedatabase:
Soiwrotethefollowingprogram:
#include<iostream>
#include<conio.h>
#include<iomanip>
#include<string.h>
#include<stdlib.h>
intcheckinarray(char[],char*);
usingnamespacestd;
classstudent
{
private:
intsem;
floatcgpa;
charpassword[11];
charpasswordtrial[11];
voidreaddata();
voidcheckpassword();
voidcreatepassword();
public:
charname[50];
introll;
http://stackoverflow.com/questions/39819294/dynamicinitalisationsofcobjectsbasedonuserinput?noredirect=1#comment66930009_39819294 1/10
10/2/2016 databasedynamicinitalisationsofc++objectsbasedonuserinputStackOverflow
voidprintdata();
charUSN[11];
staticintnumber;
voidopendatabase();
voidfirsttime();
public:
student(charn[50]="NONE")
{
number++;
roll=number;
cout<<endl<<"Newrecordunderthenameof"<<n<<"hasbeencreated!"<<endl;
cout<<"Rollnumbersetfornewstudentas:"<<roll<<endl;
cout<<"UsethisRollnumberforfurtherusage"<<endl<<endl;
};
};
voidstudent::opendatabase()
{
intch;
cout<<"Enteryourname:"<<endl;
cin>>name;
cout<<"Enteryourpassword"<<endl;
cin>>passwordtrial;
if(!strcmp(passwordtrial,password))
{
cout<<"Doyouwanttoreadorwrite";
cin>>ch;
switch(ch)
{
case0:
readdata();
break;
case1:
printdata();
break;
}
}
else
cout<<"TryAgain";
};
voidstudent::readdata()
{
cout<<endl<<"Enterthenameofthestudent:";
cin>>name;
cout<<endl<<"Enterthesemesterofthestudent:";
http://stackoverflow.com/questions/39819294/dynamicinitalisationsofcobjectsbasedonuserinput?noredirect=1#comment66930009_39819294 2/10
10/2/2016 databasedynamicinitalisationsofc++objectsbasedonuserinputStackOverflow
cin>>sem;
cout<<endl<<"Enterthecgpaofthestudent:";
cin>>cgpa;
};
voidstudent::printdata()
{
cout<<"Thenameis:"<<name<<endl;
cout<<"Thesemis:"<<sem<<endl;
cout<<"Therollis:"<<roll<<endl;
cout<<"Thecgpais:"<<cgpa<<endl;
}
voidstudent::firsttime()
{
cout<<"Enteryourname:";
cin>>name;
cout<<"Hey"<<name<<"WelcometoDBMS"<<endl;
createpassword();
};
voidstudent::createpassword()
{
cout<<"Pleaseenteryour6characterpassword..:";
cin>>password;
cout<<"PleaseInputyourDatahere....:";
readdata();
};
intstudent::number=0;
intmain()
{
enumstatus{existing,newacc,exit};
enumfuncti{read,update};
charentry1[40];
charentry[10];
charusn[15];
chara[1000][15];
charn[40];
inti,j=0,k;
ints=2;
cout<<endl<<"WELCOMETOCOLLEGENAME"<<endl<<"PressentertoaccessDatabase...";
getch();
cout<<endl<<"WelcometotheMainPageofourDatabase:"<<endl;
while(1)
{//Useroption
cout<<endl<<"Doyouwanttoaccessanoldentry:"<<endl<<"OR"<<"CreateaNEW
entry:";
cin>>entry1;
if(!strcmp(entry1,"old"))
http://stackoverflow.com/questions/39819294/dynamicinitalisationsofcobjectsbasedonuserinput?noredirect=1#comment66930009_39819294 3/10
10/2/2016 databasedynamicinitalisationsofc++objectsbasedonuserinputStackOverflow
s=existing;
elseif(!strcmp(entry1,"new"))
s=newacc;
else
s=exit;
switch(s)
{
caseexisting:
{
i=1;
break;
}
casenewacc:
{i=1;
cout<<endl<<"Enteryourusn:"<<endl;
cin>>usn;
strcpy(a[j],usn);
j++;
strcpy(n,usn);
cout<<n;
studentusn(n);
usn.firsttime();//Starthere!!useitogotonext
looporstayinthisloop,,changenameentrytousn
break;
}
default:{cout<<"ErrorInput";i=0;break;}
}
if(i)
continue;
cout<<endl<<"Whatdouwanttodo??"<<endl<<"ReadEntries"<<endl<<"Update
entries";
cin>>entry;
if(!strcmp(entry,"read"))
s=read;
elseif(!strcmp(entry,"update"))
s=update;
else
s=exit;
cout<<endl<<"Enteryourusn:"<<endl;
cin>>usn;
if(checkinarray(a[15],usn))
{
switch(s)
http://stackoverflow.com/questions/39819294/dynamicinitalisationsofcobjectsbasedonuserinput?noredirect=1#comment66930009_39819294 4/10
10/2/2016 databasedynamicinitalisationsofc++objectsbasedonuserinputStackOverflow
{
caseread:{
usn.printdata();
break;
}
caseupdate:{
usn.firsttime();
break;
}
default:
cout<<"Areyousureyouwanttoexit?"<<endl<<"Press0
toexit"<<endl<<"tobacktomenupress1";
cin>>k;
break;
}
if(!k)
break;
elsecout<<"InvalidRollnumbertryagain!";
}
intcheckinarray(chara[][15],charb[])
{
intlen;
//Findingthelengthofthestring:
len=(sizeof(a)/sizeof(a[0]));
//CheckingConditionsforrollnumber:
for(intk=0;k<len;k++)
{
if(strcmp(a[k],b))
return1;//stringcompare!!
}
return0;
}
okaysowhenirunthisigetthefollowingerror:
http://stackoverflow.com/questions/39819294/dynamicinitalisationsofcobjectsbasedonuserinput?noredirect=1#comment66930009_39819294 5/10
10/2/2016 databasedynamicinitalisationsofc++objectsbasedonuserinputStackOverflow
requestformember'printdata'in'usn',whichisofnonclasstype'char[15]'AND
requestformember'firsttime'in'usn',whichisofnonclasstype'char[15]'
Sopleasehelpmeovercomethiserrorbysuggestingdifferentwaystocreateandcallobjectsbased
onuserinput
edited32minsago asked1hourago
VijayKalmath
1 2
1 PleasereduceyourcodetoanMinimal,Complete,andVerifiableexample.Allanswersatthispointwillbe
basedonguesswork.user458130159minsago
whyareyouusingthesameidentifierforastudentobjectandchararray?Tryusing: student
newStudent(n); andthen newStudent.firsttime(); peval27 38minsago
@VijayKalmathInaddition,Ihopeyouareusingmultipleheaderandbodyfiles,otherwiseitbecomesa
messtounderstand.peval2736minsago
1)iamtryingtodothatsothattheobjectnameisthesameastheusername2)Ifiuseanewstudent(n)
thenthesecondtimeiwanttocreateanewobjectitgetsthesamenameasthefirstloop..
VijayKalmath 35minsago
@VijayKalmathUnlessIamnotunderstandingwhatyouaredoing,youdon'tneedtousethesame
variablename.PleasefollowwhatIwassuggesting.peval2732minsago
@user4581301Idon'tseeanyanswer/commentfromPavanChandaka.Whatdoyoumean? peval27 31
minsago
@user4581301fewcommentsaboveyouwrote:Stillnotminimal,butprovesPavanChandaka'sguess
correct.peval2727minsago
@peval27btwimadeasmalladjustmenttothecode....Iamnotusingadifferentvariablebecause....the
firsttimethewhileloopisexecutedtheobjectiscreatedwiththenamenewstudent(likeusuggested)but
theduringthesecondwhilelooprunifichoosetocreateanewentry...thenewobjectcreatedthenwould
havethenamenewstudenttherebywritingoverthepreviouslyexistingobject. VijayKalmath 25mins
http://stackoverflow.com/questions/39819294/dynamicinitalisationsofcobjectsbasedonuserinput?noredirect=1#comment66930009_39819294 6/10
10/2/2016 databasedynamicinitalisationsofc++objectsbasedonuserinputStackOverflow
havethenamenewstudenttherebywritingoverthepreviouslyexistingobject. VijayKalmath 25mins
ago
Thecodeisdifficulttofollow.Howeveritlookslikeyouneedtostoreareferenceofthenewcreated
student(forexampleinalistofstudents),ifyouwanttoaccessexistingstudentsandcreatenew
students.peval2721minsago
yes...Iuseanarraytostorerecordspresent...andusethisarraytocheckifaparticularrecordispresent
andisavailabletoedit..Sorryforthestyleofcode...Newtoprogramming VijayKalmath 17minsago
PavanChandakapostedananswerthatprovedcorrectbasedonaneducatedguess.Maybehegota
downvotebarrageanddeletedit.user45813011minago
1Answer
OP'sproblemcanbereducedtothefollowingexample:
#include<iostream>
#include<string.h>
usingnamespacestd;
classstudent
{
public:
student(charn[50]="NONE")
{
}
};
intmain()
{
charusn[15];
charn[40];
{
cin>>usn;
strcpy(n,usn);
studentusn(n);
}
usn.printdata();
}
http://stackoverflow.com/questions/39819294/dynamicinitalisationsofcobjectsbasedonuserinput?noredirect=1#comment66930009_39819294 7/10
10/2/2016 databasedynamicinitalisationsofc++objectsbasedonuserinputStackOverflow
ThisiswhatismeantbyaMinimal,Complete,andVerifiableexample.Noteverything,but
everythingneededtoreproducetheproblem.ThebeautyoftheMCVEisithasreducedthe
problemtothepointwhereallofitcanfitonthescreenandprobablywithinthebrain,makingit
easytoanalyzeandtest.
Thingstonote:
Therearetwovariablesnamed usn
charusn[15];
studentusn(n);
Annotatingthisblocktobetterexplainwhatishappening,weget
{
cin>>usn;//usescharusn[15];
strcpy(n,usn);
studentusn(n);//declaresanewvariablenamedusnthatreplacescharusn[15];for
theremainderofthisblock
}//studentusn(n);endsrighthereandisdestroyed.
usn.printdata();//usescharusn[15];whichhasnoprintdatamethod.
Sohowdowefixthis?
1. studentusn(n); musthaveawiderscope.
2.oneofthesetwovariablesmustchangenamesbecauseonce studentusn(n); haswider
scopeitwillcollidewith charusn[15];
Letsgivethataquicktry.
intmain()
{
charusn[15];
charn[40];
studentstud(n);
http://stackoverflow.com/questions/39819294/dynamicinitalisationsofcobjectsbasedonuserinput?noredirect=1#comment66930009_39819294 8/10
10/2/2016 databasedynamicinitalisationsofc++objectsbasedonuserinputStackOverflow
{
cin>>usn;
strcpy(n,usn);
}
stud.printdata();
}
intmain()
{
charusn[15];
charn[40];
student*stud;
{
cin>>usn;
strcpy(n,usn);
stud=newstudent(n);
}
stud>printdata();
deletestud;
}
intmain()
{
charusn[15];
charn[40];
std::unique_ptr<student>stud;
{
cin>>usn;
strcpy(n,usn);
stud.reset(newstudent(n));
}
stud>printdata();
}
std::unique_ptr takescareofthat.But...Whataboutthatwholedatabasething?Whynotstore
stud inalist?
http://stackoverflow.com/questions/39819294/dynamicinitalisationsofcobjectsbasedonuserinput?noredirect=1#comment66930009_39819294 9/10
10/2/2016 databasedynamicinitalisationsofc++objectsbasedonuserinputStackOverflow
intmain()
{
charusn[15];
charn[40];
std::vector<student>studs;
{
cin>>usn;
strcpy(n,usn);
studs.emplace_back(n);//orstuds.push_back(student(n));
}
for(student&stud:studs)
{
stud.printdata();
}
}
std::vectorsolvesbothproblemsatonce.
answered4minsago
user4581301
8,248 2 8 22
AnswerYourQuestion
http://stackoverflow.com/questions/39819294/dynamicinitalisationsofcobjectsbasedonuserinput?noredirect=1#comment66930009_39819294 10/10