如何检查用户的输入是否有效以及我正在寻找的数字?

How can I check if a user's input is both valid and also a number I'm looking for?

本文关键字:数字 寻找 有效 是否 何检查 检查 输入 用户      更新时间:2023-10-16

如何创建一个条件语句来防止进入失败状态,并在数据无效或数据不是 1、2、3 或 4 时要求用户提供新数据?

int choice;
while ( !choice || choice != 1 || 2 || 3 || 4){
cout << "Entry Invalid. Enter again: ";
cin >> choice
}

例如,如果用户输入"f",则失败状态将被处理,程序将请求新数据。当他们输入 5 时,程序会说"不是有效数字",并要求新数据。

对于stoi,您需要C++11

标准
int choice;
string inp;
cin >> inp;
while(inp != "1" && inp != "2" && inp !="3" && inp !="4"){
cout << "Wrong input , type again" << endl;
//system("PAUSE");
cin >> inp;
}
choice = stoi(inp);
cout << choice;

这个确切的问题在第一年给我带来了太多麻烦。这应该可以满足您的需求,也许可以尝试实现最大失败尝试次数。

int choice = 0;
while (true) {
cout << "Please enter a number between 1 and 4" << endl;
cin >> choice;
if (cin.fail()) {
cout << "Invalid input" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}
else if (choice < 1 || choice > 4) {
cout << "Not a valid number" << endl;
}
else {
break;
}
}
cout << "You chose " << choice << endl;