When people get bored, they usually do something fun. When I get bored, I write a new blog post.
So yesterday, I was working on an assignment which was a C++ program. I had code similar to this:
Okay, so its pretty simple. I'm asking for a integer from the keyboard, and then i need a char. I'm using "getline" because I wanted to count spaces as well.
Should have worked ... but it didn't:
After I enter the number and press ENTER, it doesn't ask me for the next input.
ZOMG what happened! Why does it skip the.getline and terminate the program? That question kept haunting me for a while... Until I found out why. I found the answer on this site called mathbits
So it turns out that the "cin" input steam function ignored the trailing "\n" in the input stream ...
The getline on the other hand, keeps reading until it FINDS a "\n" ... See how that works?
Since the previous "Cin" kept a trailing "\n", the getline found it and thought it was the end of the input!
The solution is well presented on mathbits as well.
One solution is to use cin.ignore(100,'\n'). This ignores up to a 100 characters in the stream, until it meets a "\n" .
Another solution is to use a dummy string variable to absorb the nasty \n :
Well done! You have now managed to overcome the \n getline problem.
The people have spoken
comments powered by Disqus