标签:c infinite-loop
参见英文答案 > Infinite loop with cin when typing string while a number is expected 4个
我正在编写这个代码作为家庭作业(刚开始C所以请放轻松).我们刚刚开始的同时,今天和今天的循环.该程序运行正常,但如果您在程序要求输入整数时输入一个字母,它会无限循环.到底是怎么回事? (以下代码)
***编辑:为了澄清,循环的部分是:“您输入的数字是负数.请输入正数以继续.”但是用户没有机会输入另一个号码.它只是继续打印这个.
#include <iostream>
using namespace std;
int main ( )
{
//define variables
int num1, num2, total;
char answer1;
do
{
//user enters a number
cout << "\nPlease enter a positive number and press Enter: \n";
cin >> num1;
//check that the given num1 value is positive
while (num1 < 0)
{
cout << "The number you entered is negative.\nPlease enter a positive number to continue.\n";
cin >> num1;
}
cout << endl;
//add the sum of 1 through num1 value
num2 = 1;
total = 0;
while (num1 >= num2)
{
total = total + num2;
num2 ++;
}
//tell the user the sum
cout << "The total of all the integers\nfrom 1 to " << num1 << " is: \n";
cout << total;
//ask if the user wants to try again
cout << "\n\nWould you like to try again with a new number?\nEnter y for yes or n for no.\n";
cin >> answer1;
} while (answer1 == 'y');
cout << endl;
return 0;
}
解决方法:
这就是basic_istream的工作原理.在您的情况下,当cin>> num1输入错误 – 设置failbit并且不清除cin.所以下次它将是相同的错误输入.要正确处理此问题,您可以添加检查输入正确,并在输入错误时清除&忽略cin.例如:
#include<limits>
//user enters a number
cout << "\nPlease enter a positive number and press Enter: \n";
do {
while(!(cin >> num1)) {
cout << "Incorrect input. Please try again.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if(num1 < 0) cout << "The number you entered is negative. Please enter a positive number to continue.\n";
} while(num1 < 0);
标签:c,infinite-loop 来源: https://codeday.me/bug/20190915/1805489.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。