I've just came across this bit of code that allows users to input strings in the command prompt. I'm aware of what they do and it's all great. But I have a question in regards to the cin and getline() functions.
string name ;
cout << "Please enter your full name: " ;
cin >> name ;
cout << "Welcome " << name << endl ;
cout << "Please enter your full name again please: " ;
getline(cin , name) ;
cout << "That's better, thanks " << name << endl ;
return 0 ;
Now when this is output, I get something along the lines of: (using john smith as the input)
Please enter your full name: john smith
Welcome John
Please enter your full name again: That's better thanks Smith
I understand why this happens, the getline is still reading from the input buffer and I know how to fix it. My question is, why is there no newline coming after the "Please enter your full name again: "? When I alter the code to:
string name ;
cout << "Please enter your full name: " ;
cin >> name ;
cout << "Welcome " << name << endl ;
cout << "Please enter your full name again please: " ;
cin.ignore( 256, '\n') ;
getline(cin , name) ;
cout << "That's better, thanks " << name << endl ;
return 0 ;
Suddenly I get a newline after you enter your full name again. It's not really a huge issue to be honest. But I wouldn't mind knowing what happened if anyone can help me. Thanks!
You see, when you enter "John Smith" as a input first
cin >> name
will not read the entire line, but the the contents of the line until the first space.So, after the first
cin
, name variable will containJohn
. There will still beSmith\n
in the buffer, and you've solved this using:Note: As Konrad Rudolph suggested, you really shouldn't use 256 or any other magic numbers in your code. Rather use
std::numeric_limits<std::streamsize>::max()
. Here is what docs says about the first argument toistream::ignore
:Because you're not outputing one to the stdout, and the user didn't get chance to press Enter.
getline
will readSmith\n
from the buffer, and it will continue immediately. It will not echo any newline characters to your console -getline
doesn't do that.It is the newline that user enters with the
Enter
key, it is not coming from your program.Edit Pressing Enter in terminal usually (depending on the terminal setup) does few separate things:
\n
into the input buffer