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:
This doesn't work properly cause getline() will see the \n left by the last input and accepts the string as nothing.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; }
What I usually end up doing is this:
Is there a more proper way to dump the newline character from the stream?Code:// CODE HERE char dumpNL; // To dump the \n cout << "Input a number: "; cin >> number; cin.get(dumpNL); // Clears the \n // CODE HERE



LinkBack URL
About LinkBacks



You see that a lot with the "Are you sure?" prompts.