I have written a C++ program in which a user need to input a character. My problem is it's working fine for the first time but as it goes through the code second time, it skips the cin statement and takes the previous defined value.
how can i make cin statement work for the second time also?
cin will assign data into your variable up to the first space it finds. If you are entering a name for example say "John Smith", so I would suggest that yiou use somthing like:
1 2
string name;
getline(cin, name);
Depending on how you are using the cin you may need to flush its buffer before using it further with cin.ignore. We would need to see you code block to better understand the issue if this doesn't help you.
void hotel::input () {
cout<<"HOTEL NAME : ";
cin>>hotelname;
cout<<"NO OF ROOMS : ";
cin>>nofrooms;
cout<<"NO OF ONE BEDROOM ROOMS : ";
cin>>nofonebdrms;
cout<<"NO OF TWO BEDROOM ROOMS : ";
cin>>noftwobdrms;
cout<<"Address : ";
cin>>address;
}
void main() {
int ch,j;
char answer;
system("CLS");
cout<<setw(10)<<"WELCOME\n";
X:
system("CLS");
cout<<setw(10)<<""<<"HOTEL RESERVATION\n";
cout<<setw(5)<<""<<"==========================\n";
cout<<"1.HOTEL DETAILS\n";
cout<<"2.UPDATE HOTEL DETAILS\n";
cout<<"3.RESERVING A ROOM\n";
cout<<"4.CANCELLING A RESERVATION\n";
cout<<"5.DISPLAY THE PRESENT STATUS\n";
cout<<"6.EXIT\n";
cout<<"ENTER YOUR CHOICE: ";
cin>>ch;
cin.ignore();
cin.clear();
switch(ch) {
case 2:
{
system("CLS");
Y:
int nofrooms,nofonebdrms,noftwobdrms;
char hotelname[50],address[50];
ofstream fout("HOTELDETAILS.dat",ios::app);
ht.input();
fout.write((char*)&ht,sizeof(ht));
fout.close();
cout<<"DO YOU WISH TO CONTINUE UPDATING ?(Y/N)";
cin.ignore();
cin>>answer;
if(answer=='y'||answer=='Y')
goto Y;
goto X;
}
}
when the code goes through ht.input(), it skips lots of cin statements in the input function and always take answer as case 2 for the second loop. Please help.