- 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?

30th Aug 2017, 6:27 PM
Rohnek Kdosi
4 Réponses
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
30th Aug 2017, 10:29 PM
Zeke Williams
Zeke Williams - avatar
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
30th Aug 2017, 9:45 PM
aklex
aklex - avatar
- 1
ok, thanks
30th Aug 2017, 6:29 PM
Rohnek Kdosi
- 1
thank you
31st Aug 2017, 5:32 AM
Rohnek Kdosi