Switch Case using strings

Started by
11 comments, last by unrealfragmaster 20 years ago
@Bovine13:
Please cease and desist using and recommending the use of <iostream.h>. It is pre-standard, meaning that there are no guarantees about what exactly is in it - or even that it will exist. Use, and recommend, <iostream> instead, noting that entities within it are defined as being in the std namespace.
Advertisement
// No, I'm not really serious about this, I did some ugly hacking// here just for recreation's sake. Oluseyi (and other // knowledgeable types), please don't hurt me :D But as a general// principle, case statements are kind of ugly, and would like to// be replaced by a calculation, or else a polymorphic dispatch.// If you really need to be able to "switch on strings" (i.e. // more than one character long), look up std::map. You can make // a map from std::string to function objects, and then do a // lookup in the map and invoke operator() on the result.std::string ethics[4] { "lawful ", "neutral ", "chaotic ", "true "};std::string morals[3] { "good", "neutral", "evil" };std::string charalign;cin >> alignchoice;alignchoice -= 'a';// implement "default" case of true neutralif (alignchoice < 0 || alignchoice > 8) alignchoice = 4; int charethic = alignchoice / 3;int charmoral = alignchoice % 3;// fix "neutral neutral" to say "true neutral" instead. // Deliberately obfuscated to provide an exercise for the reader. // ;)if (charethic & charmoral & 1) charethic |= 2;charalign += charethic; // er, addition *is* overloaded for concatenation in std::string // isn't it? I learned C++ in the Old Days(TM) and kinda missed // out on the details of this stuff...charalign += charmoral; // you could do the concatenation instead using std::stringstream // if you have to, I guess. Or just use a single lookup table // instead of decomposing the alignments like I have :)


(Edit: wow, maybe I should line-wrap my comments...)

[edited by - Zahlman on April 11, 2004 8:58:03 PM]
@Zahlman:

Interesting approach, but you should have gone all the way and changed the user prompts (subtracting the integer value of ''a'' from charalign is less than intuitive). Indexing the options by number (and reading the inputs into an integer) instead would have eliminated all that logic.

There''s nothing wrong with or ugly about switch statements, btw. Don''t be unnecessarily prejudiced against language features (including goto, when appropriate).

Oh, an deliberate obfuscation is evil.

This topic is closed to new replies.

Advertisement