problem with cin
I am reading input from standard input using cin. I want to be able to read in newlines. The problem is that sometimes there is other stuff in the cin buffer that may have been left over. I dont want to read this in. Is there anyway that I can flush out the cin buffer to be sure that there is nothing in it. I thought that maybe I could use peek to see if there is something there and if there is then read it. But it doesnt seem to be working. I am using something like the following:
Can someone help me with this?
if(cin.peek() != EOF)
You don't have to use peek in order to call cin.ignore() - if the buffer is empty, ignore() will have no effect.
Actually, if the buffer is empty, the ignore() will wait for the user to type something and press enter.
Since the user has to hit enter before any data is sent from the console to the input stream, you can usually figure out whether there is anything left in the stream that would allow a call to ignore(). How you do that depends on what cin functions you are using to read in the previous input.
For example, if you are using cin >>, then there will always be at least a '\n' in the stream, so you can call the ignore safely. If you are using get you can check the value gotten to see if it is '\n', and if it isn't then you can call the ignore safely. If you are using getline, then no matter what you won't need the ignore because the newline is automatically discarded. If you are mixing the ones above, then you should deal with any potential extra characters and the trailing newline when you do the read instead of later before the next read.