我正在试图弄清楚如何组织我的代码,以便在我测试时它会停止导致无限循环。我输了一个字符串,它突然导致无限循环。
//填写代码以定义变量month并将其初始化为1 float total = 0,rain,month = 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
答案 0 :(得分:0)
如果std :: cin收到输入,则无法解析它将设置failbit。您可以使用!cin
对此进行测试。在您检查完故障后,请不要忘记使用cin.clear
重置故障位。