我已经检查过几个“可能已经有你答案的问题”,但仍未发现任何有效的问题。我的问题是一个简单的while循环,当评估为true时,它循环并询问用户输入,我输入一个数字,应该将while循环评估为false并退出,但它重复。我第二次输入数字。我是C ++的新手,但我假设有一些东西在我的iostream中被抬起来了。
1)我输入“0”,它将while循环计算为true并再次询问用户输入,因为它是< 1.
2)当再次提示时,我输入1,这显然不是< 1,循环再次重复告诉我“无效的数字 - 数字必须是bwt之间”
3)如果我再次输入1 ...... while循环的计算结果为false,并在步骤2中继续进行。
代码:
string question = "Enter number of days rented (1-365): ";
int getValidNumber(int num, int lowerNum, int upperNum, string question){
while((num < 1) || (num > 365)) {
cout << endl;
cout << "Invalid number -- the number must be bwtween " <<
lowerNum << " and " << upperNum << "." << endl <<
"Please try again." << endl;
cout << question;
cin >> num;
}
return num;
}
答案 0 :(得分:1)
再次查看我的代码后,我两次调用相同的函数。操作员错误。那就行了......
cin >> rentalDays;
// Validate user input
getValidNumber(rentalDays, RENTAL_DAYS_MIN, RENTAL_DAYS_MAX, RENTAL_DAYS);
rentalDays = getValidNumber(rentalDays, RENTAL_DAYS_MIN, RENTAL_DAYS_MAX, RENTAL_DAYS);