Using getline () in C ++

Last Updated On Thursday 26th Aug 2021

getline c++

If you use getline() after cin >> something, you need to flush the newline character from the buffer in between. You can do this with cin.ignore()

	string messageVar;
cout << "Type your message: ";
getline(cin, messageVar);
  • This is because the operator >> leaves a newline character \n in 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 for string objects

  • getline() is a useful function to retrieve string from input stream.

  • getline() for string objects is a normal function, not a member of istream

	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;