我正在尝试为一个练习编写此代码,该练习提出并允许用户通过输入与他们选择的饮料相对应的数字(1-5)选择饮料。然后,它将打印出来,指定他们选择了哪种饮料,如果他们输入的不是1-5,则显示错误消息。
下面是功能代码:
#include <vector>
std::string Vending (){
int num;
std::vector<std::string> beverage ={"Coke", "Sprite", "Water", "Pepsi", "7-Up"};
std::cin >> num;
switch (num){
case (1) :
std::cout << "You have chosen " << beverage[num-1];
break;
case (2) :
std::cout << "You have chosen " << beverage[num-1];
break;
case (3) :
std::cout << "You have chosen " << beverage[num-1];
break;
case (4) :
std::cout << "You have chosen " << beverage[num-1];
break;
case (5) :
std::cout << "You have chosen " << beverage[num-1];
break;
default :
std::cout << "Error, choice was not valid, here is your money back.\n";
break;
}
}
程序运行正常,但我只是想知道是否存在一种使switch()
变短的方法,例如将一个范围设置为大小写。 case(//range from 1-5)
而不是每个案例编号单独写入每个案例。
任何提示将不胜感激! :)
您根本不需要switch
或任何类型的选择,只需进行一些基本的检查即可确定输入是否在范围内,然后打印出来:
if (num > 0 && num <= beverage.size())
{
std::cout << "You have chosen " << beverage[num-1];
}
else
{
std::cout << "Error, choice was not valid, here is your money back.\n";
}
if
语句在这里更合适,因为switch
块的设计目的不是在范围内操作。
如果您必须使用switch
,并且热衷于编写可移植的C ++(因此无法选择gcc范围switch
,那么您可以编写]]
更自然]switch (num){ case 1: case 2: case 3: case 4: case 5: std::cout << "You have chosen " << beverage[num-1]; break; default : std::cout << "Error, choice was not valid, here is your money back.\n"; }
但是写起来[[far
if (num >= 1 && num <= beverage.size()){
std::cout << "You have chosen " << beverage.at(num - 1);
} else {
std::cout << "Error, choice was not valid, here is your money back.\n";
}
它具有额外的优势,我还没有对饮料的数量进行硬编码。使用at
还可以帮助您防范未定义的行为,因为始终会进行矢量边界检查。