我正在努力创建一个带有错误检查的菜单,这是我想出的,但我似乎无法让它工作。
#include <iostream>
using namespace std;
int main()
{
char option; // user's entered option will be saved in this variable
int error1 = 0;
//Displaying Options for the menu
cout << "There are three packages available." << endl;
cout << "Monthly Price - Price per MB for overages (excluding C)" << endl;
cout << "A) $15 - $.06 for each MB after 200 MB." << endl;
cout << "B) $25 - $.02 for each MB after 2,000 MB ( approx. 2 GB)." << endl;
cout << "C) $50 - Unlimited data." << endl;
do //do-while loop starts here
{
//Prompting user to enter an option according to menu
cout << "Please enter which plan you currently have : ";
cin >> option; // taking option value as input and saving in variable "option"
if(option == 'A' || option == 'a') // Checking if user selected option 1
{
cout << "You chose a" << endl;
error1 = 1;
}
else if(option == 'B' || option == 'b') // Checking if user selected option 2
{
cout << "You chose b" << endl;
error1 = 1;
}
else if(option == 'C' || option == 'c') // Checking if user selected option 3
{
cout << "You chose c" << endl;
error1 = 1;
}
else //if user has entered invalid choice
{
//Displaying error message
error1 = 0;
cout << "Invalid Option entered";
}
}
while(error1 = 0); //condition of do-while loop
return 0;
}
当输入错误的值时,输出将是 Invalid Option entered;但是,它不会循环回到开头并再次提示用户输入。
为什么要这样做?
最佳答案
改变
while(error1 = 0); //condition of do-while loop
进入这个
while(error1 == 0); //condition of do-while loop
在第一个选项中,您只需将 0 分配给 error1
,然后将 error1
测试为 bool 值,这意味着 0 为 FALSE,非 0 为 TRUE。因此,一旦 while
中的条件被评估为 FALSE,循环就结束了。
关于c++ - 为什么我的 do-while 循环不继续循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32916734/