Thread: switch string

  1. #1
    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
    28,413
    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.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    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, 03:40 AM
  3. can anyone see anything wrong with this code
    By occ0708 in forum C++ Programming
    Replies: 6
    Last Post: 12-07-2004, 12:47 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM