Using getline(cin, s) after cin [duplicate]

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.


Solution 1:

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

Solution 2:

Another way of doing it is to put a

cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' ); 

after your cin>>number; to flush the input buffer completely (rejecting all of the extra characters until a newline is found). You need to #include <limits> to get the max() method.