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);
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With