gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:59:34 25 4
gpt4 key购买 nike

这是代码片段:

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

关于c++ - 检查正确的输入会导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21177601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com