【发布时间】:2016-12-19 10:59:22
【问题描述】:
我有这样的菜单。
int choice;
cout <<"1: Exit\n2: Print Mark\n3: Print Name"<<endl;
cin >> choice;
while (choice != 1 && choice != 2 && choice != 3)
{
cout << "Invalid Choice <<endl;
cout <<"1: Exit\n2: Print Mark\n3: Print Name"<<endl;
cin >> choice;
}
这就是我目前所拥有的,但是当我输入字母时它会终止,是否有一种更简单的方法来测试无效输入。 我知道有类似 cin.fail() 但不确定如何实现它
【问题讨论】:
-
你应该做
while (choice != '1' && choice != '2' && choice != '3'),对吧? -
我刚刚给一个类似的问题写了this answer。检查其中的代码,尤其是我将
std::cin >> ...置于条件中的prt。 -
@Nishant 不,因为 OP 正在读取 整数。
标签: c++ validation input while-loop cin