【发布时间】:2019-09-26 19:35:58
【问题描述】:
我有一个菜单创建系统,其中包含用户可以从中选择的字符串向量,因此只有菜单选项中的整数才允许作为有效输入。
如果数字输入正确,一切正常。如果输入不正确(字符串、浮点数、负数等),则当它应该显示错误消息时,什么都不会发生。
如果尝试输入其他任何内容(有效或无效),则随后的每个输入都会出现错误消息,并且用户会被卡住。
这是我用来验证代码的循环 -
bool check = false;
string line;
std::stringstream temp;
int input;
while(!check)
{
getline(cin, line);
temp << line;
temp >> std::noskipws >> input; //this is supposed to reject spaces and floats
if(!temp.fail() && temp.eof() && input > 0 && input <= static_cast<int>(options.size()))
{
check = true; //returns valid value and stops loop
}
else //if all conditions aren't met
{
cin.clear();
cin.ignore();
cout << wrongInput << endl; //prints error
}
}
return input; //correctly returns when valid on first try
在此之前,我只是使用 cin >> input 和 cin.fail() 进行检查,但这允许浮点数通过并且会多次显示字符串条目的错误消息。
如果有任何缺失的信息,请告诉我,但我认为这里的一切都是相关的。
编辑:只是用正确的输入测试我的程序,它开始看似任意失败。
错误输入示例:
(menu with numbered options)
intput: "abba" || "3.2" || "4 3" || "-4" || etc.
(no response)
input: "valid number"
(please enter a number from above) - repeats indefinitely
正确输入示例:
(menu with numbered options)
input: "1"
(correctly executes "1" selection, shows menu again)
input: "1"
(again correctly executes "1" selection, shows menu again)
input: "1"
(no response)
input: "1"
(please enter a number from above) - repeats indefinitely
【问题讨论】:
-
给我们一个输入的例子。
-
如果该行包含有效的整数值,则不会设置
eof标志。在您尝试从“文件”末尾以外的地方读取之前,它不会设置。 -
我还建议您考虑the
>>operator 返回 的内容,以及如何在boolean expression 中使用流。 -
你为什么要检查
temp.eof()? -
你也永远不会在任何时候重置
temp上的错误条件
标签: c++ while-loop getline