0

Since a switch statement doesn't take in a string what other than a switch statement is there that I should use. Is there anything that I could use which won't require me to write a ton of if statements? Or is there a way to make switch statements take in a string? I need another way other than a switch statement so I can check for multiple ( > 20) different cases.

vector<string> tokens;
string present;
while(....){
string right_value = right->evaluate();  <-- finds out what the string to the right of present is 
string left_value = left->evaluate();   <-- finds out what the string to the left of present is. 
switch(present){
 case "write" : return right_value;
.
.
.
.
.
}
  • 2
    Use a map of string to function . And why do you think that using a switch is superior to using if/else? The latter is typically shorter, clearer and more flexible. I've never understood this idea that switches are some magic solution to all programming problems. –  Oct 04 '17 at 22:07
  • Depends on your use-case, in particular, the logic inside the switch cases. As you don't provide the code with this logic, the question is likely to be close as "too broad". But here is a hint: create a dictionary with wich you can translate the condition into resulting data or action. It can be an array, `std::map` or something else. – Ivan Aksamentov - Drop Oct 04 '17 at 22:09
  • 1
    You can use `if`. – Galik Oct 04 '17 at 22:10
  • @NickA the example's mentioned (using enums, etc) would take a lot of time to do. I need something simple and easily. That's why I want something similar to the switch statement – Low_level_dir Oct 04 '17 at 22:10
  • @Galik I have specified that I need it for checking multiple cases so if statements wont be a good idea – Low_level_dir Oct 04 '17 at 22:11
  • 2
    It's hard to beat a set of `if` statements. You can't avoid writing one statement per `case` whatever you do. – Galik Oct 04 '17 at 22:11
  • @Low_level_dir I still don't understand why `switch` would be any better than `if`, you're just replacing `if`/`else if` with `case`/`break` – Nick is tired Oct 04 '17 at 22:14
  • @NickA it is just very time consuming and I have to then I would have so many if statements the code would be just unbearable – Low_level_dir Oct 04 '17 at 22:18
  • 1
    How is a stack of `if` statements so different from a stack of `case` statements? – Galik Oct 04 '17 at 22:20
  • which would look nice? a bunch of : if (present == "write"){ cout << right_value << endl; } or case "write" : return right value; break: – Low_level_dir Oct 04 '17 at 22:21
  • Well I am biased because I always thought `switch/case: break;` looked clunky. :) – Galik Oct 04 '17 at 22:21
  • Or, `if(present == "write") return right_value;` – Galik Oct 04 '17 at 23:27
  • @Galik oh ya forgot that would work too – Low_level_dir Oct 05 '17 at 00:45

0 Answers0