After executing following code when I enter full name(eg:- "fjh jkgfv") with spaces after choosing II option(Write) I am stuck in an infinite loop.I think it is problem related to some input buffer.Can you please explain the error.Thanks.....
CODE
class File
{
private:
struct rec
{
char name[20];
int age;
rec()
{
age = 0;
}
}p;
fstream file;
public:
File()
{
file.open("/home/puneet/Desktop/temp.dat",ios::binary|ios::in|ios:

ut|ios::app);
if(!file)
{
cerr<<"Error opening the file"<<endl;
cerr<<"Press any key to exit . . . . . ."<<endl;
getchar();
exit(1);
}
}
~File()
{
file.close();
}
void Read()
{
file.clear();
if(file.eof() == false)
{
file.read((char *)&p,sizeof(p));
cout<<"Record"<<(file.tellg()/sizeof(p))<<":"<<endl;
cout<<"Name "<<p.name<<endl;
cout<<"Age "<<p.age<<endl<<endl;
}
}
void Write()
{
file.clear();
file.seekp(0L,ios::end);
cout<<"Your name "<<endl;
cin.getline(p.name,20); // Expected error in input & stucks in infinite loop
cout<<"Your age"<<endl;
cin>>p.age;
file.write((char *)&p,sizeof(p));
}
void Display()
{
file.clear();
file.seekg(0L,ios::beg);
while(file.read((char *)&p,sizeof(p)))
{
cout<<"Record"<<(file.tellg()/sizeof(p))<<":"<<endl;
cout<<"Name "<<p.name<<endl;
cout<<"Age "<<p.age<<endl<<endl;
}
}
};
int main()
{
File writer;
while(true)
{
system("clear");
cout<<"1.Read next account"<<endl;
cout<<"2.Write an account at the end"<<endl;
cout<<"3.Display all the records"<<endl;
cout<<"4.Exit"<<endl;
int choice = 0;
cin>>choice;
switch(choice)
{
case 1:
system("clear");
writer.Read();
cout<<"\n\nPress any key to exit . . . . . ."<<endl;
getchar();
break;
case 2: // Choose this option
system("clear");
writer.Write();
cout<<"\n\nPress any key to exit . . . . . ."<<endl;
getchar(); // Not executed
break;
case 3:
system("clear");
writer.Display();
cout<<"\n\nPress any key to exit . . . . . ."<<endl;
getchar();
break;
case 4:
return 0;
default:
break;
}
}
return 0;
}