How to using switch statement with string variables or values? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to using switch statement with string variables or values?

Hi, I am a newbie in C++ programming. I am making a CLI Calculator which will perform operations by input from the user. so I need multiple conditional statement like SWITCH but that does not work. It says it wants to be an integer one. is there anyway in which I can get string input from user and evaluate multiple conditions based on that input. Thanks in Advance

15th May 2019, 12:47 PM
Huzaifa Imran
Huzaifa Imran - avatar
2 Answers
+ 3
A switch can only use integral types, like char, int, long long. But a string is not an integral, so it can't be used there. The if ... else is the way to go in those cases. You could make a switch work with strings by implementing a compile time hashing function, which basically converts a string into an integer. But that's probably not something to dive into as a beginner. Just making you aware of it.
15th May 2019, 1:08 PM
Dennis
Dennis - avatar
0
if switches ask for numerical types, then dont make life difficult. If, else ifs, and else will replace cases and default easily 😃
15th May 2019, 4:13 PM
Choe
Choe - avatar