If you use
cin >> something, you need to flush the newline character from the buffer in between. You can do this with
string messageVar; cout << "Type your message: "; cin.ignore(); getline(cin, messageVar);
- This is because the operator
>>leaves a newline character
\nin the input buffer.
- This can become a problem when you are doing unformatted input, such
getline()as one that reads the input until a newline character is found.
getline() is a useful function to retrieve string from input stream.
getline()for string objects is a normal function, not a member of
string & getline(istream & input, string & str, char delimiter = '\n' );
For example, the following code reads one line from the input stream and saves it into a string.
string s; getline(cin, s); cout << s << endl;