使用 cin 验证用户输入
Validating user input using cin
我试图这样做: 如果该值大于 50 或小于 -50,或者不是整数,则再次使用 CIN 该值(直到它有效(
for (size_t i = 0; i < cities; i++)
{
for (size_t j = 0; j < days; j++)
{
cout << "temperature(" << i + 1 << ',' << j + 1 << ") = ";
cin >> *(temperatures + i * days + j);
while (!(*(temperatures + i * days + j) > 50 && *(temperatures + i * days + j) < -50))
{
cin.clear();
cin.ignore();
cout << "temperature(" << i + 1 << ',' << j + 1 << ") = ";
cin >> *(temperatures + i * days + j);
}
}
如果我写一个大于 50 或小于 -50 的数字,它可以工作。
但是如果我写例如:
temperature(1,1) = covid
比下一行:
temperature(1,1) = temperature(1,1) = temperature(1,1) = temperature(1,1) = temperature(1,1) =
我该如何解决这个问题?
问题是即使输入失败,您也在测试*(temperatures + i * days + j)
的值。另外,您错误地使用了忽略(仅忽略一个字符而不是所有未完成的字符(。另外,您有过于复杂的代码
这是一个更好的版本
#include <limits> // for std::numeric_limits
cout << "temperature(" << i + 1 << ',' << j + 1 << ") = ";
int temp;
while (!(cin >> temp) || temp < -50 || temp > 50)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout << "temperature(" << i + 1 << ',' << j + 1 << ") = ";
}
temperatures[i * days + j] = temp;
我使用了新的变量temp
来简化代码。我在 while 循环条件中包含cin >> temp
,因此仅在输入成功时检查 temp,并且我使用cin.ignore(numeric_limits<streamsize>::max(), 'n');
忽略输入中剩余的所有字符。
请注意,这可能并不完美。如果您输入10deg
,那么即使输入中包含非数字,输入也会成功(temp 等于 10(。如果你想正确地进行输入验证,那么唯一真正的方法是将输入读取为字符串,并在转换为整数之前测试字符串。
相关文章:
- C++如何通过用户输入删除列表元素
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 用户定义函数中的指针和输入
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- 在C++中,我如何接受不同于同一行的用户输入
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 当用户键入分隔符时,停止getline()输入
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 当用户在qtablewidget中输入单元格时,如何获得信号?C++
- 显示基于用户输入的整数的字符
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 如果用户没有输入任何内容或输入错误,如何重新输入用户的输入?
- 为什么在代码块中执行时会跳过输入用户输入的行?
- 使用 for 循环在数组中输入用户