我想知道通过使用转换string为使其与 switch 一起工作是否不会影响程序的行为。我使用字符串是因为我正在通过为此方法使用 asci 表来验证用户输入,但未包含在此代码中以使其简短。intstoi>= 48 && <= 57
编码:
do
{
cout << "Choice: ";
string userChoice;
cin >> userChoice;
isValid = validNum(userChoice);
if(isValid)
{
int intUserchoice = stoi (userChoice);
switch(intUserchoice)
{
case 1:
ServerStart();
}
}
}while (!isValid);
Run Code Online (Sandbox Code Playgroud)
我想说,只有当您将用户输入作为某种数字序列处理时,转换为数字类型才有意义。就像“如果选择是第三个以下的选项之一”。然后,您将使用 switch/case 或多个 if 来实现它,如下例所示:
void handleChoice1(string userChoice) {
int intUserchoice = stoi(userChoice);
switch(intUserchoice) {
case 1:
ServerStart();
// Heads up, no break here
case 2:
StartSomethingElse();
break;
case 3:
// more stuff..
}
}
// which is equivalent to this:
void handleChoice2(string userChoice) {
int intUserchoice = stoi(userChoice);
if (intUserchoice <= 1) {
ServerStart();
}
if (intUserchoice <= 2) {
StartSomethingElse();
}
}
Run Code Online (Sandbox Code Playgroud)
如果每个选择只有一个简单的逻辑,我认为没有理由不将输入字符串与预期选项进行比较并处理意外输入。如果这是您必须实现的唯一“菜单”,我只会使用简单的 if/else。当然,这不能扩展到大型和复杂的菜单,但对于简单的事情来说这很好。
void handleChoice3(string userChoice) {
if (userChoice == "1") {
ServerStart();
}
else if (userChoice == "2") {
StartSomethingElse();
}
else {
error("Invalid input");
}
}
Run Code Online (Sandbox Code Playgroud)