检查正确的输入会导致无限循环

时间:2014-01-17 03:59:40

标签: c++ loops infinite-loop

以下是代码段:

#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 ++的新手,我不确定这只是编译器表现得很糟糕,或者这是否属于我的行为。

1 个答案:

答案 0 :(得分:2)

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

相反,您可能希望重写为:

#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/