Using getline()

Hello everyone,

I am having this problem with getline(), where whenever my program reaches a getline() statement, i.e.:

getline ( cin, string);

instead of waiting for input, it just reads whitespace into the string and goes to the next statement. Why is this?



NewProgrammer
Last edited on
It is possible that before the getline statement some input was done and not all input data was written.
That was my first thought, too. But when I print the value of the string:

1
2
3
getline ( cin, s );

cout << s << endl; 


The value for s is "".

Also, before last night, inserting a "fake" getline() statement before the real one.:

1
2
3
4
5
6
7
string throwaway;
getline( cin, throwaway );     /* Since the first getline() call is not working for some reason, 
                                             here is a throwaway statement to keep the error from 
                                             effecting the program */

string s;
getline( cin, s );      // The "real" getline() statement 


got me around what was happening (Obviously, this did not cure the root cause). But last night, in one instance of the above code, the program started skipping over both getlines(). At that point, I realized it is time to figure out the root cause.
Last edited on
U can use getline(string,size)
Attempted it. ( cin.getline(string,size); ). Same results :-(
There is probably a leftover newline in the buffer. Try ` cin.ignore(std::numeric_limits<int>::max(),'\n'); ' before the getline call?
Will do. I have to leave for class now. I'll attempt that ASAP and get back to you.
Problem solved. Thank you, Texan40.
Texan40, while that statement has solved the problem of removing leftover input, it has created one minor one:

Let's say there is no leftover input. This statement causes the program to "wait" for the user to enter '\n' before it does anything else.

How can I instruct the program to only call that statement if there is leftover input?
try using a cin.sync(); before the getline
Last edited on
I wish I read that post two hours ago. This is a much simpler solution then what I came up with. :-) Nonetheless, I'm glad I will know it moving forward. Thanks.
Even worse, I thought I read through all the istream functions. Somehow, I overlooked sync()...
Topic archived. No new replies allowed.