0% found this document useful (0 votes)
49 views

Database - Dynamic Initalisations of C++ Objects Based On User Input - Stack Overflow

The document describes a C++ program for a college database that allows users to access student records based on their unique student number (USN). The program uses a Student class to store student data like name, roll number, semester, etc. The main function presents a menu to users to either access an existing record or create a new one. When a new record is created, a Student object is instantiated using the user's USN as the name. However, this causes errors since USN is a string and not a class. The question asks how to dynamically create Student objects based on user input.

Uploaded by

Vijay Kalmath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Database - Dynamic Initalisations of C++ Objects Based On User Input - Stack Overflow

The document describes a C++ program for a college database that allows users to access student records based on their unique student number (USN). The program uses a Student class to store student data like name, roll number, semester, etc. The main function presents a menu to users to either access an existing record or create a new one. When a new record is created, a Student object is instantiated using the user's USN as the name. However, this causes errors since USN is a string and not a class. The question asks how to dynamically create Student objects based on user input.

Uploaded by

Vijay Kalmath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

10/2/2016 databasedynamicinitalisationsofc++objectsbasedonuserinputStackOverflow

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

c++ database class object

edited32minsago asked1hourago
VijayKalmath
1 2

Canyouexplainbetterwhatyouaretryingtoachieve?Andwhat s isin switch(s) . peval27 1hour


ago

1 PleasereduceyourcodetoanMinimal,Complete,andVerifiableexample.Allanswersatthispointwillbe
basedonguesswork.user458130159minsago

IamsorryforthepreviousstyleofQuestion...Firsttime VijayKalmath 44minsago

whyareyouusingthesameidentifierforastudentobjectandchararray?Tryusing: student
newStudent(n); andthen newStudent.firsttime(); peval27 38minsago

@VijayKalmathInaddition,Ihopeyouareusingmultipleheaderandbodyfiles,otherwiseitbecomesa
messtounderstand.peval2736minsago

Stillnotminimal,butproves@PavanChandaka'sguesscorrect. user4581301 36minsago

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];

isanautomaticvariablewithin main .Itisvisibleonlywithin main andwillexpireattheendof


main

studentusn(n);

isanautomaticvariablewithinananonymousblockwithin main .Itisvisibleonlywithinthisblock


andwillexpireattheendoftheblock.

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();
}

Isn'tpossiblebecausethereisnodatain n withwhichwecanmake stud .Atleastnotforthis


minimalexample.

intmain()
{
charusn[15];
charn[40];
student*stud;
{
cin>>usn;
strcpy(n,usn);
stud=newstudent(n);
}
stud>printdata();
deletestud;
}

Solvesthatbydynamicallyallocating stud sothatitisnolongerscopedbythebraces.


Unfortunatelythatdoespickupsomeextramemorymanagementwoes. stud mustbedeleted.
Addeda delete ,butwhatif printdata throwsanexceptionand deletestud; isskipped?

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

You might also like