我正在使用C ++为项目创建菜单。在项目的特定部分,我使用switch语句来允许用户在该菜单的不同选项之间进行选择。问题是,当前允许他们多次选择相同的选项。由于每个选项都有一个特定的值,因此它会在该选项的值上加上用户选择该选项的次数。我想将用户可以选择任何选项的次数限制为一次。
编辑:不允许在该项目中使用数组。
void additionalOptionsMenu();
const double VIEW = 50.00;
const double JACUZZI = 40.00;
const double BREAKFAST = 15.00;
const double BED = 12.00;
const double WIFI = 9.00;
int main()
{
double additionalOptions = 0.00;
int subChoice;
do{
additionalOptionsMenu();
cin >> subChoice;
switch (subChoice){
case 1:
additionalOptions += VIEW;
break;
case 2:
additionalOptions += JACUZZI;
break;
case 3:
additionalOptions += BREAKFAST;
break;
case 4:
additionalOptions += BED;
break;
case 5:
additionalOptions += WIFI;
break;
case 6:
break;
default:
cout << "ERROR";
break;
}
}while (subChoice != 6);
cout << additionalOptions;
//Displays the final value of additionalOptions
return 0;
}
void additionalOptionsMenu()
{
cout << "\n1. View: $50.00\n"
<< "\n2. Jacuzzi: $40.00\n"
<< "\n3. Breakfast: $15.00\n"
<< "\n4. Extra Bed: $12.00\n"
<< "\n5. Internet Access: $9.00\n"
<< "\n6. Previous Menu\n";
}
答案 0 :(得分:0)
您不会在基本交换机的情况下找到该功能。使用变量将该功能添加到switch语句中,以检查是否已使用了选项是可行的。为此,可在代码的+ =行周围添加一条if语句。
但是,从长远来看,使用开关外壳以外的结构可能会使您的生活更轻松。
答案 1 :(得分:0)
最简单的方法是使用一系列布尔值来跟踪用户已选择的内容:
void additionalOptionsMenu();
const double VIEW = 50.0;
const double JACUZZI = 40.0;
const double BREAKFAST = 15.0;
const double BED = 12.0;
const double WIFI = 9.0;
enum AmenitysOption {
, AMENITY_NONE
, AMENITY_VIEW
, AMENITY_JACUZZI
, AMENITY_BREAKFAST
, AMENITY_BED
, AMENITY_WIFI
, AMENITY_MAX
};
bool amenityOptions[AMENITY_MAX] = {};
int main()
{
double additionalOptions = 0.0;
int subChoice;
do {
additionalOptionsMenu();
cin >> subChoice;
if(amenityOptions[subChoice]) {
cout << "\nYou've already picked that option.\n";
continue;
}
switch (subChoice) {
case AMENITY_NONE:
break;
case AMENITY_VIEW:
additionalOptions += VIEW;
amenityOptions[AMENITY_VIEW] = true;
break;
case AMENITY_JACUZZI:
additionalOptions += JACUZZI;
amenityOptions[AMENITY_JACUZZI] = true;
break;
case AMENITY_BREAKFAST:
additionalOptions += BREAKFAST;
amenityOptions[AMENITY_BREAKFAST] = true;
break;
case AMENITY_BED:
additionalOptions += BED;
amenityOptions[AMENITY_BED] = true;
break;
case AMENITY_WIFI:
additionalOptions += WIFI;
amenityOptions[AMENITY_WIFI] = true;
break;
case AMENITY_MAX:
break;
default:
cout << "\nERROR";
break;
}
} while (subChoice < AMENITY_MAX);
cout << additionalOptions;
//Displays the final value of additionalOptions
return 0;
}
void additionalOptionsMenu()
{
cout << "\n1. View: $50.00\n"
<< "\n2. Jacuzzi: $40.00\n"
<< "\n3. Breakfast: $15.00\n"
<< "\n4. Extra Bed: $12.00\n"
<< "\n5. Internet Access: $9.00\n"
<< "\n6. Previous Menu\n";
}