gpt4 book ai didi

c++ - 过滤掉无效的用户输入

转载 作者:太空宇宙 更新时间:2023-11-03 10:35:49 25 4
gpt4 key购买 nike

我正在尝试使用以下代码块在小型 C++ 程序中过滤掉无效的用户输入:

    int selection = -1;
while (!(selection >= 1 && selection <=4))
{
cin >> selection;

if (!(selection >= 1 && selection <=4))
{
cout << "invalid selection!" << endl;
cout << "selection: ";
}
}

当我输入任何在我要过滤的范围之内或之外的数值时,它似乎工作正常。然而,当我输入无效值时会发生奇怪的事情,例如大于最大可存储 int 或字符的值。代码循环并跳过“cin”命令。

我该如何解决这个问题?

谢谢

最佳答案

您需要使用 fail() 检测不可转换的输入然后忽略其余的坏数据并重置 cin使用 clear() 的错误标志在阅读新的输入尝试之前。

int selection = -1;
while (!(selection >= 1 && selection <=4))
{
cin >> selection;

if (cin.fail() || !(selection >= 1 && selection <=4))
{
cout << "invalid selection!" << endl;
cout << "selection: ";

cin.clear();

cin.ignore(std::numeric_limits<int>::max(), '\n');
}
}

关于c++ - 过滤掉无效的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3875780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com