getline() does not work if used after some inputs

Muhammad Arslan Jamshaid picture Muhammad Arslan Jamshaid · Oct 2, 2012 · Viewed 65.5k times · Source

Possible Duplicate:
Need help with getline()

getline() is not working, if I use it after some inputs, i.e.

#include<iostream>
using namespace std;

main()
{
string date,time;
char journal[23];


cout<<"Date:\t";
cin>>date;
cout<<"Time:\t";
cin>>time;

cout<<"Journal Entry:\t";
cin.getline(journal,23);


cout<<endl;
system("pause");
}

where as if I use getline() on top of inputs, it does work i.e.

cout<<"Journal Entry:\t";
cin.getline(journal,23);
cout<<"Date:\t";
cin>>date;
cout<<"Time:\t";
cin>>time;

What might be the reason?

Answer

P.P picture P.P · Oct 2, 2012

Characters are extracted until either (n - 1) characters have been extracted or the delimiting character is found (which is delimiter if this parameter is specified, or '\n' otherwise). The extraction also stops if the end of the file is reached in the input sequence or if an error occurs during the input operation.

When cin.getline() reads from the input, there is a newline character left in the input stream, so it doesn't read your c-string. Use cin.ignore() before calling getline().

cout<<"Journal Entry:\t";
cin.ignore();
cin.getline(journal,23);