我要做的是为无效的char创建一个循环,例如: 如果允许的字符是' A' a'' C'' c'并且用户输入' f' 它会说它无效并要求他们输入一个新角色,直到他们输入一个有效的角色。
我也不确定它会进入以下代码的位置:
#include<iostream>
using namespace std;
int main (){
int units;
double priceA,priceB,priceC;
char package, goAgain;
priceA=15.95;
priceB=23.95;
priceC=45.95;
do {
cout << "Enter the Package chosen. Enter 'A' or 'a' for package A.n";
cout << "Enter 'b' or 'B' for package B.n";
cout << "Enter 'c' or 'C' for package C.n";
cin >> package;
cout << "Enter the number of message units";
cin >> units;
while(units>672){
cout <<endl;
cout <<"Invalid number,please enter a value from 0 to 672."<<endl;
cout <<"Please Enter a new Number for units.";
cin >>units;
}
switch (package){
case 'A':
case 'a':
if(units>10){
priceA=15.95+(units-10)*.20;
priceB=23.95+(units-20)*.10;
cout <<"The price of Package A is" << " $"<<priceA<< endl;
}
else if(units<=10){
priceA=15.95;
cout << "The price of Package A is" << " $"<<priceA<<endl;
}
if (priceA>priceB){
cout <<"By switching to Package B you would save" << " $" << priceA- priceB<<endl;
}
if (priceA>priceC){
cout << "By switching to Package C you would save" << " $"<<priceA- priceC<<endl;
}
break;
case 'b':
case 'B':
if(units>10){
priceA=15.95+(units-10)*.20;
priceB=23.95+(units-20)*.10;
cout <<"The price of Package B is" << " $"<<priceB<< endl;
}
else if(units<=10){
priceB=23.95;
cout << "The price of Package B is" << " $"<<priceB<<endl;
}
if (priceB>priceA){
cout <<"By switching to Package A you would save" << " $" << priceB- priceA<<endl;
}
if (priceB>priceC){
cout << "By switching to Package C you would save" << " $"<<priceB-priceC<<endl;
}
break;
case 'c':
case 'C':
if(units>10){
priceA=15.95+(units-10)*.20;
priceB=23.95+(units-20)*.10;
cout <<"The price of Package C is" << " $"<<priceC<< endl;
}
else if(units<=10){
priceC=45.95;
cout << "The price of Package C is" << " $"<<priceC<<endl;
}
if (priceC>priceA){
cout <<"By switching to Package A you would save" << " $" << priceC-priceA<<endl;
}
if (priceC>priceB){
cout << "By switching to Package B you would save" << " $"<<priceC-priceB<<endl;
}
break;
}
cout<<"do you want to go again? y/n" << endl;
cin >>goAgain;
}
while(goAgain=='y');
}
答案 0 :(得分:0)
交换机可以有一个default
分支,用于处理其他case
分支中未处理的所有内容。您可以将代码放在那里,然后将整个switch
放在do
- while
循环中,如下所示:
bool valid;
do {
valid = true;
switch (package) {
case 'A':
⋮
default:
valid = false;
cout << "Invalid bla bla " << package << ", enter it again" << endl;
cin >> package;
break;
}
} while (!valid);
答案 1 :(得分:0)
您可以尝试这样的事情:
bool valid = false;
while (!valid)
{
const std::string valid_packages = "AaCc";
char package;
cin >> package;
if (valid_packages.find(package) != std::string::npos)
{
valid = true;
}
else
{
cout << "\n"
<< "Invalid package name, try again.\n";
}
}
有效的包裹字母放在一个字符串中。根据有效字母串检查用户的输入。如果找到用户的输入,则标志valid
设置为true,结束循环。