On occasions you may need to clear unwanted data in an input stream, most commonly keyboard input. This may be after a call to a read function that failed to input all available data, or it may be to ensure that the user doesn't try the "type ahead" approach when using your application.
In C++ the cin is used to take input from user. Sometimes for some reasons some error flags are set. In that time the cin does not take any input. Sometimes it takes some other characters. So if we clear the cin, then the error flags are reset.
The cin. ignore() function is used which is used to ignore or clear one or more characters from the input buffer.
The program works as it should whenever you enter an Int, but for the case you enter an invalid datatype I want it to ask for input again.
I would prefer the C++ size constraints over the C versions:
// Ignore to the end of file
cin.ignore(std::numeric_limits<std::streamsize>::max())
// Ignore to the end of line
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
Possibly:
std::cin.ignore(INT_MAX);
This would read in and ignore everything until EOF
. (you can also supply a second argument which is the character to read until (ex: '\n'
to ignore a single line).
Also: You probably want to do a: std::cin.clear();
before this too to reset the stream state.
cin.clear();
fflush(stdin);
This was the only thing that worked for me when reading from console. In every other case it would either read indefinitely due to lack of \n, or something would remain in the buffer.
EDIT: I found out that the previous solution made things worse. THIS one however, works:
cin.getline(temp, STRLEN);
if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
I have found two solutions to this.
The first, and simplest, is to use std::getline()
for example:
std::getline(std::cin, yourString);
... that will discard the input stream when it gets to a new-line. Read more about this function here.
Another option that directly discards the stream is this...
#include <limits>
// Possibly some other code here
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Good luck!
int i;
cout << "Please enter an integer value: ";
// cin >> i; leaves '\n' among possible other junk in the buffer.
// '\n' also happens to be the default delim character for getline() below.
cin >> i;
if (cin.fail())
{
cout << "\ncin failed - substituting: i=1;\n\n";
i = 1;
}
cin.clear(); cin.ignore(INT_MAX,'\n');
cout << "The value you entered is: " << i << " and its double is " << i*2 << ".\n\n";
string myString;
cout << "What's your full name? (spaces inclded) \n";
getline (cin, myString);
cout << "\nHello '" << myString << "'.\n\n\n";
How about:
cin.ignore(cin.rdbuf()->in_avail());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With