Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a good practice: Converting string to int?

Tags:

c++

I want to know if converting string to int by using stoi to make it work with switch is not effecting the behavior of a program. I am using string because I am validating user input by using asci table for this >= 48 && <= 57 method but not includes in this code to make it short.

The code:

    do
       {
          cout << "Choice: ";
          string userChoice;
          cin >> userChoice;
          isValid = validNum(userChoice);
          if(isValid)
          {
             int intUserchoice = stoi (userChoice);
             switch(intUserchoice)
             {
             case 1:
                ServerStart();
             }
          }
       }while (!isValid);
like image 475
Ali-Baba Avatar asked Nov 06 '22 04:11

Ali-Baba


1 Answers

I'd say that the conversion to a numeric type only makes sense, if you handle the user input as some kind of numeric sequence. Like "If the choice was one of the options below the 3rd". You will then implement it with a switch/case or mulitple ifs like these examples:

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 there is only a simple logic for each choice, I see no reason to not just compare the input string to expected options and handle an unexpected input. If this is the only "menu" you'll have to implement I would just go with a simple if/else. Of course this does not scale to big and complex menus, but for simple things this is fine.

void handleChoice3(string userChoice) {
    if (userChoice == "1") {
        ServerStart();
    }
    else if (userChoice == "2") {
        StartSomethingElse();
    }
    else {
        error("Invalid input");
    }
}
like image 79
hansmaad Avatar answered Nov 27 '22 02:11

hansmaad