switch string

This is a discussion on switch string within the C++ Programming forums, part of the General Programming Boards category; Hello.. Is there any way to make a string switch in c++ to make my code look better instead of ...

  1. #1
    l2u
    l2u is offline
    Registered User
    Join Date
    May 2006
    Posts
    630

    switch string

    Hello..

    Is there any way to make a string switch in c++ to make my code look better instead of using if and else if for each case? Like in .net?

    For instance:

    Code:
    string str = "test";
    switch(str) {
    	case "test":
    		break;
    	case "test":
    		break;
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,758
    No, since the switch may only be used with integral types, or a type convertible to an integral type. So even if it does compile, you would probably end up with a very wrong answer.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,325
    If you have a lot of strings, you can write a functions that work for each possible string, then put them in a map with the string as the key and the function pointer as the value. This is the command pattern. Then, when you have your string you just execute myFunctionMap[str].

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 06-30-2008, 02:48 PM
  2. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 02:40 AM
  3. can anyone see anything wrong with this code
    By occ0708 in forum C++ Programming
    Replies: 6
    Last Post: 12-07-2004, 11:47 AM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 01:45 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21