Question:
C++ using cin.ignore() to flush buffer?
hunchback
2012-03-21 07:35:00 UTC
Hi,

I have a loop in my program which uses getline to get user input. So I have to use cin.ignore() at the top of the loop to flush the '\n' at the end of the last input, from the previous cycle of the loop.

The problem with that is, the first time the loop is encountered, there's nothing in the buffer, so the cin.ignore() statement just prints a blank line waiting for something to ignore, without any hint as to why it's doing this. Is there any way to insert a '\n' into the buffer at the beginning of the program, so the cin.ignore() ignores that, instead of waiting for the user to input something to ignore?
Four answers:
James Bond
2012-03-21 08:28:29 UTC
Why dont you think of using

cing.putback(char) function
cja
2012-03-21 15:14:46 UTC
If you're using getline you don't need cin.ignore. If you're using >> to extract from cin, maybe you do need cin.ignore, but I almost never do that. Just use getline, your life will be easier.
2012-03-21 14:37:37 UTC
Can't you just check the buffer for '\n' and flush if it exists, ignore if it doesn't?
2012-03-21 14:42:06 UTC
after flushing, you giv a new line character


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...