Does cin.sync() always work?

Hi guys (and girls),

For clearing the input stream, I know that you can use cin.sync();, but does that always work (in other words, is it guaranteed to clear the input stream)?

I read in a few places that it's not required to do anything....
In that case, what would be the best way to clear the input stream? (or is there even any way to do it?)
(assuming that the input stream may or may not already be empty; we don't know)

(note that for the most part, I just use getline and stringstreams to get user input, so I don't really need to know this -- I'm just wondering)


(also note that I joined these forums so I can help others, but I'm so mean and cruel that I didn't want to make my first post in someone else's thread :-), and I didn't know what else to say here)
> For clearing the input stream, I know that you can use cin.sync();, but does that always work?

No. You can't reliably use sync() to do anything on input streams.
If a get area exists, the effect is implementation-defined. - IS



> what would be the best way to clear the input stream? (or is there even any way to do it?)

The only portable way to 'clear' an input buffer is by reading and discarding characters until a particular character (for example a new line) occurs or a limit is reached. For example:

1
2
std::cin.clear() ; // to be safe, clear error flags which may be set
std::cin.ignore( std::numeric_limits<std::streampos>::max(), '\n' ) ;


There is no way using standard C++ facilities to 'clear everything in the stdin buffer till it is empty'.
Last edited on
Topic archived. No new replies allowed.