Simple question with the getline() function.
Is there a proper way to dump the newline character from the input stream so you can use the getline() function without it screwing up?
For instance:
Code:
#include <iostream>
#include <string>
using namespace std;
int main() {
int number;
string textLine;
cout << "Input a number: ";
cin >> number; // Takes the number, leaves the \n
cout << "Enter a string:" << endl;
getline(cin, textLine);
cout << "You wrote the number " << number << " and the line:" << endl
<< textLine;
cin.get();
return 0;
}
This doesn't work properly cause getline() will see the \n left by the last input and accepts the string as nothing.
What I usually end up doing is this:
Code:
// CODE HERE
char dumpNL; // To dump the \n
cout << "Input a number: ";
cin >> number;
cin.get(dumpNL); // Clears the \n
// CODE HERE
Is there a more proper way to dump the newline character from the stream?