Heng Aik Hwee
Heng Aik Hwee

Reputation: 159

how to use switch case to take a string parameter?

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;
}

Upvotes: 0

Views: 2178

Answers (2)

Bart Friederichs
Bart Friederichs

Reputation: 33521

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
}

Upvotes: 0

Cogman
Cogman

Reputation: 2150

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.

Upvotes: 3

Related Questions