问题
Okay I'm very new to C++, I'm experianced with C# and I don't really know what is wrong in my code. I'm just trying to figure out how to check whether the user's input is a integer or string.
But when I type 'a' or some other string, the while loop never ends.
#include <iostream>
using namespace std;
int main ()
{
int number;
goto skip;
do
{
cout << "Wrong input. Try again.";
skip:
cout << "Number: ";
cin >> number;
}
while (!cin);
cout << "Correct input.";
system("PAUSE");
}
回答1:
Once your stream has gone into failure mode it will stay in failure mode until you clear()
its state bits. However, merely clearing the bits won't help because the offending character will stay in the stream. Most likely you want to ignore the entire line before retrying:
while (!(std::cout << "Number: " && std::cin >> number)) {
std::cout << "Wrong input. Try again.\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "Correct input.\n";
std::cin.ignore();
来源:https://stackoverflow.com/questions/19128005/stuck-in-loop-while-trying-to-get-input-from-cin