【问题标题】:Input Validation, want numbers but not strings.. code is resulting in infinite loop输入验证,需要数字而不是字符串..代码导致无限循环
【发布时间】:2015-07-19 21:48:44
【问题描述】:

我试图弄清楚如何组织我的代码,以便在我测试它时停止导致无限循环。我输入了一个字符串,结果突然死循环了。

// 填写代码定义并初始化为1的变量month 浮动总计 = 0,雨,月 = 1;

cout << "Enter the total rainfall for month " << month << endl;
cout << "Enter -1 when you are finished" << endl;
// Fill in the code to read in the value for rain
cin >> rain;

// Fill in the code to start a while loop that iterates 
// while rain does not equal -1
if(cin.fail())
{
        cout << "You have inputted an invalid value." << endl << "Please enter an integer value for rain. (-1 to exit)";
        cin >> rain;
}
while (rain != -1)
{

    // Fill in the code to update total by adding it to rain
    // Fill in the code to increment month by one

    cout << "Enter the total rainfall in inches for month "
         << month << endl;
    cout << "Enter -1 when you are finished" << endl;
    // Fill in the code to read in the value for rain

【问题讨论】:

    标签: c++ validation loops input infinite


    【解决方案1】:

    如果 std::cin 接收到它无法解析的输入,它将设置一个故障位。您可以使用!cin 对此进行测试。勾选后不要忘记使用cin.clear重置failbit。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-04
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2021-08-03
      相关资源
      最近更新 更多