Every newbie eventually comes accross one very obvious problem with cin: they need a way to clear it's buffer. Obviously, many people turn to
cin.ignore()
, but that function isn't meant for that purpose. Others use API calls.
Well, there is a way, and it's really quite simple:
while(cin.rdbuf()->in_avail() > 0) cin.get();
EXCEPT this
does not work! At least not by default..... ;)
You see, I learned today that usually, the standard input and output streams for the C++ and C I/O functions are synced. What this means is that none of the standard input functions manages it's own, completely independent buffer. This is why
in_avail()
will read zero, even though it's definitely more than zero...
The fix? Quite simple:
1 2 3 4 5 6
|
//a single call in main should do the trick:
int main(int count, char **vec)
{
cin.sync_with_stdio(false); //tells cin not to sync with the C io functions' buffers
return 0;
}
|
Now try the code to clear cin's buffer. It works! That's because
cin
(the C++ way) doesn't sync with
stdin
(the C way) anymore, and manages a completely independent buffer. It then becomes a trivial action to clear input.
I just thought this was somthing everyone should know, since I couldn't find anything on it when I was new to C++...
If I made any mistakes, please feel free to correct me.