这是否是一个好的做法:将字符串转换为整数?

5
我想知道是否将 string 转换为 int 使用 stoi 会影响程序的行为,导致它不能与 switch 一起正常工作。
我使用 string 是因为我使用 asci 表验证用户输入,这是使用 >= 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);

3
你可以简单而安全地使用它,但还有更有效的方法。来源 - Саша
4
这个基本上看起来没问题,虽然细节不够多,无法确定。我会怀疑 validNumstoi 有点多余,但是验证用户输入、将其转换为整数或枚举类型,并根据结果切换的基本模式是有效的。 - Nathan Pierson
2
@Ranoiaetep 这可能会错误地接受像“1.7”这样的输入。如果不知道validNum具体检查了什么,很难说完全使用stoi进行等效检查的样子是什么。 - Nathan Pierson
2
@Ali-Baba 是的,但是 >='0' && <= '9'>=48 && <=57 更易读。 - Stefan Riedel
1
你是因为更喜欢使用 switch/case 而不是 if/else,还是因为你在 case 中没有使用 breakreturn 才使用它们? - hansmaad
显示剩余14条评论
1个回答

1

我认为只有当您将用户输入处理为某种数字序列时,将其转换为数字类型才有意义。比如,“如果选择是以下选项中的第三个”,那么您可以使用类似于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();
    }
}

如果每个选择只有简单的逻辑,我认为没有理由不直接将输入字符串与期望选项进行比较并处理意外输入。如果这是您需要实现的唯一“菜单”,我建议使用简单的 if/else 语句。当然,对于大型和复杂的菜单,这种方法并不可扩展,但对于简单的事情来说,这是可以接受的。
void handleChoice3(string userChoice) {
    if (userChoice == "1") {
        ServerStart();
    }
    else if (userChoice == "2") {
        StartSomethingElse();
    }
    else {
        error("Invalid input");
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接