-
Clearing cin buffer
I was tinkering with a recent program I made for my programming class which determines the difference between the ages of two people and I discovered a little bug: If the person enters something other than a numerical value, cin kinda wacks out. Here is the code I'm using to fix the problem:
Code:
int ErrorHandler()
{
if(std::cin.fail())
{
std::cerr << "Input error \n";
std::cin.clear(); //Reset input failure indicators
//Flushing buffer
char BadInput[5];
std::cin >> BadInput;
return 0;
}
else
{
return 1;
}
}
It works, but if the user enters more than 4 characters, the program either ignores it or gives me an exception of some sort. Is there a better way to flush the buffer (I'm sort of a newb so I'm not to familiar with the methods for doing this yet)?
-
It's not a bug, it's intentional.
As for clearing out the buffer, let me look something up...
Code:
// I think this should work:
std::cin.ignore(std::cin.rdbuf()->in_avail());
-
What does this code do (just thought I'd ask before I try to use it)? And isn't the -> operator for accessing member functions/variables on the free store?
-
-> is for accessing members via a pointer. This pointer might point to the heap, but doesn't have to.
Let's see.
The first executed part is
std::cin.rdbuf()
which returns a pointer to the stream buffer that underlies the stream. Every stream in C++ (cin, cout, instances of ifstream, ofstream etc.) has an underlying stream buffer, which is an object of a class derived from basic_streambuf.
The next part is ->in_avail() which is called on the pointer to the stream buffer. It returns the number of characters that are currently availble. You can read this many characters and be guaranteed that your app won't need to wait for user input or something like that.
Finally this value is passed to std::cin.ignore() which tells cin to ignore the next n characters, where n is the argument passed to ignore.
In effect the line of code tells cin to ignore all characters currently available.
-
Wow, it works perfectly (and I think I actually understand it). Why do I have to use a pointer to the streambuffer though? Does the streambuffer exist in a special part of memory or something? I've read in my C++ book that you can only access certain parts of memory using pointers. Thanks for all the help Corned Bee.
-
Because rdbuf() returns a pointer. That's simply the way it is.