Using getline(cin, s) after cin

pauliwago picture pauliwago · Apr 21, 2011 · Viewed 76.9k times · Source

I need the following program to take the entire line of user input and put it into string names:

cout << "Enter the number: ";
int number;
cin >> number;

cout << "Enter names: ";
string names;

getline(cin, names);

With the cin >> number command before the getline() command however (which I'm guessing is the issue), it won't allow me to input names. Why?

I heard something about a cin.clear() command, but I have no idea how this works or why this is even necessary.

Answer

Cristiano Miranda picture Cristiano Miranda · Jul 8, 2012
cout << "Enter the number: ";
int number;
cin >> number;

cin.ignore(256, '\n'); // remaining input characters up to the next newline character
                       // are ignored

cout << "Enter names: ";
string names;
getline(cin, names);