- 1
Switch for strings?
Hi there, I have a wuestion again, this time, I'm asking if you can use the switch statement use even for strings, I tried it, and it did not work. Is it possible, or am I wasting my time trying?
5 Respostas
0
You could try to make a map of strings with the values being characters or integers. For example:
#include <map>
#include <string>
map<string, int> myMap; // order of string and int is important
string words[] = {"Apple", "Orange", "Pear", "Cabbage"};
int wordsSize = sizeof(words)/sizeof(string);
for (int i = 0; i < wordsSize; ++i) {//initialize map with words
myMap[words[i]] = i;
}
// now you can use the switch with the words
int switchInt = myMap["Orange"]; // switchInt = 1
switch (switchInt) {
case 0:
cout << "It's an apple!" << endl;
break;
case 1:
cout << "It's an orange!" << endl;
//etc...
}
EDIT: https://code.sololearn.com/ctqt3x2Gcf37
0
It's not possible without really overcomplicating things compared to just using if statements. Switches don't support strings, because then the compiler wouldn't be able to make jump tables with them
- 1
ok, thanks
- 1
thank you