问题
I'm fairly new to programming, and I'm trying to filter inputs from cin
(for no particular reason; It is the only input method I know of right now) such that one can only enter 1-10 and get the "positive" response. Here is my code:
#pragma region Check cin is a valid input (an integer between 1 and 10, not a string or number out of range)
int input;
bool valid2=false;
while (!valid2)
{
cout << "Enter an integer (1-10): ";
cin >> input;
if (!cin || input > 10 || input < 1)
{
cout << "Error: Invalid. Try again." << endl << endl;
cin.ignore(numeric_limits<streamsize>::max());
cin.clear();
}
else
{
valid2 = true;
}
}
#pragma endregion
Ignore the "pragma", I have one test script with blocks for each little experiment to save me time and this is just how I collapse them when they're no longer valid.
My problem (among others) is that when I enter a non-integer such as f
, it loops infinitely with "Error: Invalid. Try Again"
, and I can't figure out why. I thought maybe since input
became defined, it was running past cin
when it comes back around. But I checked an isolated example, and cin
let me specifically redefine input
before continuing.
Sidebar: Speaking of pragma
, does anyone have a better method for this in c++? Aside from making individual methods, because most of my tests can just run inside main
.
EDIT:
I've switched cin.ignore(...)
and cin.clear()
and now the program can properly filter the inputs; however now, it doesn't loop back at all. After giving me "Error: Invalid. Try again."
, it hangs where it should ask me again to enter the integer.
回答1:
Your original code has TWO problems (at least as far as I've spotted - not guaranteeing there aren't any more):
- The order of
cin.clear()
andcin.ignore()
-cin.clear()
should be beforecin.ignore()
, orcin.ignore()
will do nothing. - The
cin.ignore(numeric_limits<streamsize>::max());
is reading until the delimiter, which defaults toEOF
- in other words, no matter what input is in the buffer, or entered after, it keeps on accepting it.
To fix both problems use this:
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
that will read until the end of the current line, which is probably more along the lines of what you want.
Oh, and change:
cin >> input;
if (!cin || input > 10 || input < 1)
to:
if (!(cin >> input) || input > 10 || input < 1)
来源:https://stackoverflow.com/questions/18131903/why-is-this-code-snippet-infinitely-looping