0

How do I take string input as a switch case parameter? I am able to do it with an int but not string.

The below code would be working if I was using an int input, but if I change to string it won't work.

#include <iostream>
#include <sstream>
#include <string>
#include <math.h>
class MissionPlan //start of MissionPlan class
{
    public:
    MissionPlan();
    float computeCivIndex(string,int,int,float,float);
}; //end of MissionPlan class

LocationData::LocationData()
{
    switch(sunType)
    {
        case "Type A": //compute 
                      break;
        case "Type B": //compute
                       break;
         //and many more case..
        default: break;
    }
}
int main()
{

    for(;;)
    {
    MissionPlan plan;
    }
    return 0;
}
1
  • I haven't touched C++ in over 12 years, but I'm pretty sure you can't. Commented Oct 22, 2012 at 17:38

2 Answers 2

3

You cannot use a switch statement on a string in C++, sorry. You're best bet here is to use an enum. If you don't want to use an enum, then your only other option would be to do a bunch of if elses that check the strings for equality.

Sign up to request clarification or add additional context in comments.

Comments

0

C/C++ doesn't support switch statements with strings. Use if-else-if instead:

if (sunType.compare("Type A") == 0) {
     //compute
} else if (sunType.compare("Type B") == 0) {
     // compute
} else {
     // default
}

2 Comments

cant i use if(sunType=="Type A") { //compute} ??
I do not develop in C++ that much, but I do not see a overloaded == operator for the std::string class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.