C++ Switch Statement Using Strings

Readers sometimes ask me the same question often enough that I feel compelled to provide the answer on my blog so that everyone has the benefit of seeing it. C++ does have a switch statement, but you need to use a numeric value with it as described in my book, C++ All-In-One for Dummies, 3rd Edition (see page 233 for details). A number of C# developers who are also learning to use C++ have asked me about using strings in the switch statement, which is clearly impossible without some fancy programming technique.

Fortunately, I have found a method for implementing switches using strings on CodeGuru. As the author states, it’s not a perfect solution and you may not find it works for you, but it is an ingenious coding technique and you should at least look at it. It’s better than saying the goal isn’t achievable using any means. To get a better idea of the methods other coders have used to overcome this problem, check out online discussions, such as Why switch statement cannot be applied on strings?.

Of course, I’m always on the lookout for other good solutions to reader problems. If you have a solution to this issue of using strings with the C++ switch statement, please contact me at John@JohnMuellerBooks.com. I always want to keep the door open to an even more innovative solutions. In the meantime, keep those e-mails coming!