【问题标题】:Validating user input using cin使用 cin 验证用户输入
【发布时间】:2020-05-26 09:12:28
【问题描述】:

我正在尝试这样做: 如果该值大于 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) = 

我该如何解决这个问题?

【问题讨论】:

    标签: c++ validation input


    【解决方案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 &gt;&gt; temp,因此仅在输入成功时才检查 temp,我使用 cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\n'); 忽略输入中剩余的所有字符。

    请注意,这可能并不完美。如果您输入了10deg,那么即使输入中包含非数字,输入也会成功(temp 等于 10)。如果你想正确地进行输入验证,那么唯一真正的方法是将输入作为字符串读取,并在转换为整数之前测试字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 1970-01-01
      • 2014-05-26
      • 2016-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多