Need to use cin.ignore(); twice for some reason...

So, for those who don't know, you can use cin.ignore(); at the end of the program in order to create a "Press Enter to end program." But for some reason, on my latest project, I needed to use cin.ignore(); twice in order to get the desired effect. Notice the last few lines of both pictures and their differences.

Here is the glitched code: http://scr.hu/0tid/qh0m4

Here is the fixed code with 2 cin.ignore(); lines: http://scr.hu/0tid/lrjq4

Can anyone think of a reason why this might happen?
When you press enter to confirm input you also insert a newline character.
Formatted input/output operations stop as soon as they find a character they can't interpret as part of a number, but that character is left in the buffer together with whatever comes after.
So after the last operation you are left with a newline in the input buffer, ready to be read or ignored.
Last edited on
Oh, okay. I fixed the problem with ry = cin.get(); after the last cin to read the newline character that's left. Thank you very much for the help!
There's nothing wrong with calling ignore 2 times. You can also do cin.ignore(2);
Or maybe you need to ignore everything that has been left in the buffer.

1
2
3
4
5
6
#include <limits>

...
   cin.clear(); // Clear any error states
   cin.ignore(std::numeric_limits<std::streamsize>::max(),  '\n'); 

Hm... Okay, thanks for the feedback!
@maeriden: I just thought using cin.ignore(); twice just looked strange so, if possible, I was going to try to fix that. And... I just wasn't sure why I had to do that in the first place.

@jlb: I haven't heard of cin.clear(); before so, perhaps I can use that next time. As you can tell, I am a complete beginner to C++ so, I'm still learning the various objects and thigs like that.
Last edited on
Topic archived. No new replies allowed.