Is it possible to use string in switch case? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Is it possible to use string in switch case?

i want the user to enter the right string with some choices and i thought using if else statement is kinda ineficient so i tried using switch case but i only got an error, is there a way for me to use string in switch case statement

19th Apr 2021, 2:25 AM
Ejingo
Ejingo - avatar
2 Answers
+ 5
No, std::string cannot be used with switch case. https://stackoverflow.com/questions/650162/why-the-switch-statement-cannot-be-applied-on-strings Probably the simplest solution is to use a map to map the string to a enum variant which can be used in the case statements, as demonstrated in this answer https://stackoverflow.com/a/27391233 However, you can also make a hash function that hashes a string into an integer. Marking the hash function constexpr will make the compiler compute the results at compile time, thus reducing the runtime overhead of hashing. It is demonstrated here, although even I don't understand what is happening in the hash function https://stackoverflow.com/a/46711735
19th Apr 2021, 3:52 AM
XXX
XXX - avatar
19th Apr 2021, 3:04 AM
Ipang