dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: Mutiple cases for the same block of a switch code?

  1. #1
    Join Date
    May 2006
    Posts
    102

    Mutiple cases for the same block of a switch code?

    Is there an easy way to have multiple cases execute the same block of code? For example, part of my code asks the user to insert three numbers as shown below.

    cin >> x;

    switch (x)
    {

    case 123 : cout << "This is just a test";
    break;

    ....//more code
    }


    Now, I want the program to print out "This is just a test", if the user enters 123 or any combination of those numbers (i.e. 123, 132, 213, 231, 321, or 312). Is there any easy way to do this or do I have to copy and paste the entire section of code for all of the possible combinations?

    Thanks!

  2. #2
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,559

    Re: Mutiple cases for the same block of a switch code?

    Code:
    switch (x)
    {
    
    case 123 : 
    case 321:
    case 231:
         cout << "This is just a test";
    break;
    
    ....//more code
    }
    You may want a more elegant way of coming up with all combinations of 123, but that's how to handle multiple values for a case.

  3. #3
    Join Date
    May 2006
    Posts
    102

    Re: Mutiple cases for the same block of a switch code?

    Hey, thanks man

    Yeah, I hear you on the elegance factor. Having to code all the possible combinations is going to take some serious manpower. I suppose smarter people than myself have already created functions or methods that will greatly reduce the necessity of having to manually enter all the combos. I'll see what I can find

  4. #4
    Join Date
    Aug 2007
    Posts
    858

    Re: Mutiple cases for the same block of a switch code?

    I would say you'll be much better off using strings to check the input.

    Code:
    int input;
    cin >> input;
    
    stringstream ss;
    ss << input;
    string temp = ss.str( ); // or just use boost::lexical_cast<string>(input);
    
    if ((temp.size( ) == 3) && (temp.find_first_not_of("123") == string::npos))
    {
      // input is some combination of 1 2 and 3
    }

  5. #5
    Join Date
    May 2006
    Posts
    102

    Re: Mutiple cases for the same block of a switch code?

    Speedo,

    Wow, thanks. I've never heard of sstream before, but I just looked into that and it worked perfectly. Now, if only I had known that before I wrote about 2 hours worth of cases

    K, time for me to go read up on sstream.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)