Switch statement with char*?

Started by
16 comments, last by ChaosPhoenix 21 years, 7 months ago
quote:Original post by biovenger
return (strcmp(c1, c2) < 0)
In addition to SabreMan''s comment, I''d like to point out that strcmp returs zero if its paremeters are equal.
Advertisement
Just to try and clarify what people have said so far, when comparing c-style strings with == or switch an important thing to realise is that you''re not comparing the contents of the strings, just the addresses of their first character.

This is almost certainly not what you want.

Helpful links:
How To Ask Questions The Smart Way | Google can help with your question | Search MSDN for help with standard C or Windows functions
You could use enums... these can be used with a switch statement

switch(computer) {case COMPUTER_1:   ...   break;case COMPUTER_2:   ...   break;} 
I''d suggest having a look at the std::map class, you can map a unique string onto a function or map it to an enum value.
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
there is a code solution to this problem over on www.codeguru.com
if(strcmp){}
else if(strcmp){}
else if(strcmp){}
else {}
quote:Original post by Paradigm Shifter
I'd suggest having a look at the std::map class, you can map a unique string onto a function or map it to an enum value.
Hmmm...

  void addToComputer1(int time) { computer1.time += time; }void addToComputer2(int time) { computer2.time += time; }...map<string, void(*)(int)> dispatcher;dispatcher["Computer1"] = addToComputer1;dispatcher["Computer2"] = addToComputer2;...map<string, void(*)(int)>::const_iterator i = dispatcher.find(tempString);if (i == dispatcher.end()) throw logic_error("blah");(*i).second(time);  

...that might be a bit confusing to some people

[edited by - Beer Hunter on September 3, 2002 7:09:18 PM]
Probably not useful for you, but if you have single-char commands, you can do this:
    switch((int)(char)*szCommand) {    case 0x41: // A (can one use case "A": here?)    case 0x47: // G    } 
You can make this more complicated if you allow 4 chars, or if only the first 4 count:
    switch(*(int *)Command) {    case 0x41424344: // ABCD    case 0x47414D45: // GAME    } 
That would require that all commands are at least 4 chars, or that the following data always are the same/cleard.

EDIT: Making the int usigned would probably be a good idea

[edited by - CWizard on September 3, 2002 8:56:32 PM]

This topic is closed to new replies.

Advertisement