我已经搜索了这个答案,似乎没有人知道如何解决这个错误。我希望输入严格地是一个 int。如果输入是双精度,我希望它发送错误。
int creatLegs = 0;
string trash;
bool validLegs = true;
do
{
cout << "How many legs should the creature have? ";
cin >> creatLegs;
if(cin.fail())
{
cin.clear();
cin >> trash; //sets to string, so that cin.ignore() ignores the whole string.
cin.ignore(); //only ignores one character
validLegs = false;
}
if (creatLegs > 0)
{
validLegs = true;
}
if (!validLegs)
{
cout << "Invalid value, try again.\n";
}
} while (!validLegs);
它似乎几乎可以工作。它发送错误,但仅在进入下一个循环之后。我怎样才能解决这个问题?为什么它仍然显示错误消息但在显示之前仍然继续?