【发布时间】:2017-06-03 13:29:43
【问题描述】:
我正在尝试验证 char 的简单输入,但如果用户在没有输入 char 的情况下按下 enter,它只会在控制台中打印一个空白行,直到输入字符。我想接受输入键作为无效输入并继续我的验证,而不是只去一个空行。
cout << "Enter room type. (S)tandard or (P)remium: ";
char roomType;
cin >> roomType;
while (cin.fail() || roomType != 's' && roomType != 'S' && roomType != 'p' && roomType != 'P')
{
cin.clear();
cin.ignore(80, '\n');
cout << "Error. Enter room type again: ";
cin >> roomType;
}
cin.ignore(80, '\n');
cin.clear();
return roomType;
【问题讨论】:
-
我在@KeeganHeffernan 下面更新了我的答案。请检查它是否适合您(它适合我)。
标签: c++ validation