Reputation: 859
I have some code that basically looks like this
int a;
cin>>a;
if(!cin.good())
{
std::cin.clear();
std::cin.ignore(2);
// set some default value for 'a' and display some messages
}
this works fine if I give an integer (as expected) or if I try to mess with it a little and give upto 2 chars. eg. 'ss' , but if I give a 3 char input 'sss' , the last 's' is not ignored and is accepted as the input for some more cin's that I have in my program down the line.
Is there any way to count the number of characters in the standard input (buffers?) after the first cin has happened, so I can safely ignore all of them.
Upvotes: 0
Views: 2004
Reputation: 153820
It is quite unclear what you mean but one meaning could be that you want to ignore all characters on the current line. You don't need to know the number of characters to do so:
std::cin.ignore(std::numeric_limits<std::size_type>::max(), '\n');
The above statement will ignore all the characters until it has extracted a newline character.
Upvotes: 2
Reputation: 2990
Doing some Googling I have found this article on how to cope with extraneous characters in cin.
Apparently it is not a good practice to use >>
on std::cin
directly. Use it like this,
int a;
std::string line;
std::getline( cin, line );
std::stringstream ss( line );
if ( ss >> a )
// Success
// Failure: input does not contain a valid number
Since we are reading till \n
each time using std::getline()
, extraneous characters are also extracted from std::cin
and put into line
.
Upvotes: 0
Reputation: 29646
How does this work? It should ignore everything available in the input buffer, preventing that third s
from being consumed later. It uses std::basic_streambuf::in_avail
.
std::cin.ignore(std::cin.rdbuf()->in_avail());
If that fails to work, you can try to ignore until you reach a line feed.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Upvotes: 3