我有一个简单的函数,它接受 1 或 2,如果这两个数字都没有输入,则重新提示输入。现在,如果我输入任何数字,它会一直停留在请求有效输入上。我知道这很容易,但我现在看不到。我错过了什么?
#include <iostream>
#include <string>
using namespace std;
int userChoice();
int main()
{
userChoice();
return 0;
}
int userChoice()
{
int input = 0;
cout << "Enter 1 or 2: ";
cin >> input;
while (input != 1 || input != 2 || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.ignore(1000, '\n');
}
cout << "Enter only 1 or 2: ";
cin >> input;
}
return input;
}
最佳答案
while
中的条件格式不正确。这将永远是正确的。
你需要使用类似的东西:
while ( !cin || (input != 1 && input != 2) )
策略变更建议
我认为使用递归函数会更好:
int userChoice()
{
int input = 0;
cout << "Enter 1 or 2: ";
cin >> input;
// If we get a valid input, return.
if ( cin && (input == 1 || input == 2))
{
return input;
}
// If there is any error in reading, clear the stream.
if ( !cin )
{
cin.clear();
cin.ignore(1000, '\n');
}
// Call function again.
return userChoice();
}
关于c++ - 简单的用户输入验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33470671/