flushing input buffer using cin
I am having a problem if someone inputs a sentence with spaces in it.
Here is some code:
Code:
const int MAXNAME = 20; // maximum no. of characters in name
const int MAXADDR = 30; // maximum no. of characters in address
struct Node
{
char strName[MAXNAME];
char strAddress[MAXADDR];
int age;
Node* link;
};
typedef Node* Node_Ptr;
void main()
{
Node temp_ptr;
char choice;
cout << "Would you like to enter a record?(y/n)" << endl;
cin >> choice;
cin.clear();
cout << "Enter Name: (lastname,firstname)" << endl;
//cin >> temp_ptr.strName;
cin.getline(temp_ptr.strName, MAXNAME);
cout << "Enter Age: " << endl;
cin >> temp_ptr.age;
cout << "Enter Address: " << endl;
cin >> temp_ptr.strAddress;
return;
}
If I use cin >> temp_ptr.strName I only get the string to the first blank space. If I use cin.getline(temp_ptr.strName, 20); the execution doesn't stop. Like there's something in the buffer, but I clear the cin before I as for the name. The endl will flush the output buffer after the cout.
I know I could read the data in seperately(breaking at white spaces), but know I'm curious.
Thanks in advance
flushing input buffer using cin
add
cin.seekg(0,ios::end);
between
cin >> choice and cin.getline()