我正在尝试在主函数的底部创建一个嵌套循环,如果用户输入“y”,程序将重复,如果“n”,该函数将返回0并停止,如果用户输入其他一些字母给出错误,重新输入选择。
如果我输入“y”,程序会重复 如果我输入“n”,我什么都不会像空白一样 如果我输入“e”,我会陷入无限循环
int main()
{
//local constants
const string ENTER_DAYS_RENTED = "Enter the number of days rented: ";
const string ENTER_MILES_DRIVEN = "Enter number of miles driven: ";
//local variables
char userCarTypeChosen;
char anotherBill;
int daysRented;
int milesDriven;
double carCharge;
double mileageCharge;
double tax = 0;
double total = 0;
do
{
//call function to display program description
displayProgramDescription();
//calls function to validate the car choice input by user
userCarTypeChosen = validateCarChoice();
//if car type chosen is suv (S) then only prompt will be to enter days
//rented, if not prompt both days rented and miles driven.
if (userCarTypeChosen == 'S')
{
daysRented = validateNumEntry(ENTER_DAYS_RENTED);
cout << endl;
}
else
{
daysRented = validateNumEntry(ENTER_DAYS_RENTED);
cout << endl;
milesDriven = validateNumEntry(ENTER_MILES_DRIVEN);
cout << endl;
}
//blank lines between input and output
cout << endl << endl;
//calls function to calculate total car charge
carCharge = calculateTotalCarCharge(userCarTypeChosen, daysRented);
//calls function to calculate total mileage charge
mileageCharge = calculateTotalMileageCharge(userCarTypeChosen,
daysRented, milesDriven);
calculateBillTotal(carCharge, mileageCharge, tax, total);
printBill (userCarTypeChosen, daysRented, milesDriven, carCharge,
mileageCharge, tax, total);
cout << endl;
cout << "Calculate another bill (y/n)? ";
cin >> anotherBill;
anotherBill = toupper(anotherBill);
cout << endl;
}
while (anotherBill == 'Y');
if (anotherBill !='N')
cout << "Error - Calculate another bill (y/n)?" << endl;
cin >> anotherBill;
return 0;
}
更新: 创建了这个功能
char validateCalcNewBill()
{
char billAgain;
cout << "Calculate another bill (y/n)?";
cin >> billAgain;
cout << endl;
billAgain = toupper(billAgain);
while (billAgain != 'Y' && billAgain !='N')
{
cout<< "Error - Calculate another bill (y/n)?";
cin >> billAgain;
billAgain = toupper(billAgain);
}
return billAgain;
}
然后在主
结束时//calls function to validate calculating a new bill
anotherBill = validateCalcNewBill();
}
while (anotherBill == 'Y');
return 0;
}
答案 0 :(得分:0)
尝试使用while循环而不是if-else语句来捕获其他答案。
char anotherBill = 'Y';
while (anotherBill != 'N')
{
if(anotherBill == 'Y')
{
cout<<"Process...\n";
cout<<"Calculate another bill? (y/n):";
cin>>anotherBill;
anotherBill = toupper(anotherBill);
}
else
{
cout<<"Invalid input. Please re-enter:";
cin>>anotherBill;
anotherBill = toupper(anotherBill);
}
}