【问题标题】:Checking for proper input leads to infinite loop检查正确的输入会导致无限循环
【发布时间】:2014-01-17 03:59:39
【问题描述】:

这里是sn-p的代码:

#include <iostream>

using namespace std;

int main ()
{
    double degree;

    do {
        cout << "Enter a temperature in degrees Celsius: ";
        cin >> degree;
    } while (cin.fail());


    //reassigns degree to conversion to farenheit
    degree = degree * (9/5) + 32;

    cout << "Your temperature in degrees Farenheit is: " << degree;
    return 0;
}

如果输入无效,程序将进入无限循环,不断重复第一个 cout。

我对 C++ 有点陌生,我不确定这是否只是编译器的行为不正常,还是我自己的问题。

【问题讨论】:

  • 你不想cin.eof()吗?
  • eof() 函数有什么作用?
  • 它在我链接的页面上解释了这一点。
  • 不直接相关,但您很快就会注意到(9/5)1 完全相同(因为整数除法忽略余数)。可能最简单的方法是输入1.8

标签: c++ loops infinite-loop


【解决方案1】:

发生这种情况是因为cin.fail() 没有按照您的想法行事。 cin.fail() 测试输入中的错误。就cin.fail() 而言,eof(文件结尾)不是输入错误。

你可能想改写为:

#include <iostream>

using namespace std;

int main ()
{
    double degree;

    while( (cout << "Enter a temperature in degrees Celsius: ")
            && !(std::cin >> degree)) {
        cout << "you entered in the wrong type, please try again" << endl;
        cin.clear();// clear error flags from cin
        cin.ignore(numeric_limits<streamsize>::max(), '\n'); //extracts characters from the stream and discards them until a newline is found 
    }


    //reassigns degree to conversion to farenheit
    degree = degree * (9.0/5) + 32; //need to do floating point division here

    cout << "Your temperature in degrees Farenheit is: " << degree;
    return 0;
}

查看此链接了解更多信息:http://www.cplusplus.com/reference/ios/ios/fail/

【讨论】:

  • 我试过这样做,但如果我输入一个非整数/双精度输入,它只会进入一个无限循环。
  • @Retrosaur,请参阅我的编辑以改进代码以及一些 cmets/解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-04
  • 1970-01-01
  • 2021-01-07
  • 2014-06-18
  • 2016-05-01
  • 2011-08-23
  • 1970-01-01
相关资源
最近更新 更多