c++ - 使用 cin 验证用户输入
问题描述
我正在尝试这样做:如果该值大于 50 或小于 -50,或者不是整数,则再次输入该值(直到它有效)
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
来简化代码。我包含cin >> temp
在 while 循环条件中,因此仅在输入成功时才检查 temp,并且我过去常常cin.ignore(numeric_limits<streamsize>::max(), '\n');
忽略输入中剩余的所有字符。
请注意,这可能并不完美。如果您输入 say10deg
那么即使输入中包含非数字,输入也会成功(temp 等于 10)。如果您想正确地进行输入验证,那么唯一真正的方法是将输入作为字符串读取,并在转换为整数之前测试该字符串。
推荐阅读
- javascript - 将滚动位置刷新到当前锚名称属性
- javascript - td 元素未解析为 int
- javascript - 返回导出模块的最佳方式
- vue.js - Vuejs - 如何使用 v-for 获取数组中的所有唯一值(删除重复项)
- scala - Scala 不能转换类型 Publisher[Publisher[_ <: T]] 不能应用于 (Flux[Flux[String]]
- django - 如何使用 Keycloak Token 获取权限列表
- python - 如何取消制表符(-1 制表符)?
- kubernetes - 如果命令返回码非零,如何终止 kubernetes 作业
- excel - VBA 帮助 - 通过调用函数运行 3 个宏的脚本不会运行所有宏
- rest - 在 Oracle APEX AJAX On demand 过程中调用 POST Web 服务