getline() problem

/plzz tell me why the string p is not being asked when the program is executed ?

#include <iostream>
#include <string>

using namespace std;

int main()
{

string c;
getline (cin,c);

int g,j;
cin>>g>>j;
string p;
getline (cin,p);

return 0;
}
Because after you get j, there is still a new line '\n' from pressing enter. Put cin.sync(); before the getline(cin, p);
Thanks, L B. This resolved a problem I was experiencing with an infinite loop because a getline command was "apparently" being skipped. Now I know what was really happening.

Is there a way to discard the extra new line character other than by using cin.sync();, and would it be a good rule of thumb to always include that line prior to using getline?
@LB, wouldn't a simple .get() do the same tihng?

like..
(cin>>g>>j).get();

?
You could use cin.get() if you can guarantee that there's only one character in the stream. It's safer to use cin.sync().

would it be a good rule of thumb to always include that line prior to using getline?

Putting it before a getline masks the actual culprit (usually cin>>) and could actually hide a bug. If the stream is supposed to be empty at a certain point, then it should be empty. It's better to find the actual culprit and put the stream clearing code after that call. Besides, you'll be introducing a bunch of redundant calls using that rule.
Topic archived. No new replies allowed.