Switch case & strings

Is it possible to use switch case with string value?

example:

void setup()
{
    Serial.begin(9600);
    while(!Serial.available()) SPARK_WLAN_Loop();
    String cmd = "start";
    switch (cmd)
    {
        case "start":
            Serial.println("ok");
            break;
        case "stop":
            Serial.println("stop ok");
        default:
            Serial.println("bad command");
            l = 1;
            // if nothing else matches, do the
            // default (which is optional)
    }        
}

this code does’nt work…
thanks for help

Nope, this is not possible.

switch() case constructs only work for ordinal/integral types and strings/char-arrays are not.

But this actually is not a Spark question but a standard C thing.

3 Likes

Right, but you could try something like putting all of your possible commands into an array of Strings, and then comparing the String argument to each element in the array:

String cmd[] = {"Start", "Stop", "Run", "Hide"}; //array of possible commands

String myCommand = "Stop"; // your command

void setup()
{
  Serial.begin(9600);
  int i = -1;
  for (i = 0; i <= sizeof(cmd)/sizeof(cmd[0]); i++) // notice the less than or equal to comparison
  {
    if (myCommand.equals(cmd[i])) // compare String myCommand and Array Element
    break;
  }
  switch (i) 
  {
    case 0:
      Serial.print("command was: ");
      Serial.println(myCommand);
      break;
    case 1:
      Serial.print("command was: ");
      Serial.println(myCommand);
      break;
    case 2:
      Serial.print("command was: ");
      Serial.println(myCommand);
      break;
    case 3:
      Serial.print("command was: ");
      Serial.println(myCommand);
      break;
    default: 
      Serial.println("Bad Command");
  }
}

void loop()
{
  
}

I hope that gives you something to work with...

5 Likes

Thanks very much

Hi I am running to issue with something similar to this type of command.

int Threshold;
void setup() {
Serial.begin(9600);
}

void loop() {
   Threshold=random(10);
***ThresholdPro();***
}
'void ThresholdPro()'{
switch(Threshold)
    {
    case '1':
    printf("Set High Voltage");
   // int HV=(digitalRead());
    break;
    case '2':
    printf("Set Low Voltage");
   // int LV=(digitalRead());
    break;
    case '3':
    printf("Set High Current");
  //  int HI=(digitalRead());
    break;
    case '4':
    printf("Set Low Current");
   // int LI=(digitalRead());
    break;
    case '5':
    printf("Set High Temp");
   // int HT=(digitalRead());
    break;
    case '6':
    printf("Set Low Temp");
   // int LT=(digitalRead());
    break;
    case '7':
    printf("Clear ");
    //Mask all bit ~ clear any Lows
    break;
    case '8':
    printf("Reading 22-bytes from EEPROM");
    //read bye and adress xx
    break;
    case '9':
    printf("What is Current Offset");
  //  int OFFset=(digitalRead());
    break;  
    case '10':
    printf("Clear all");
    Threshold=0;
    break;
    
    default: 
    printf("Normal Setting");
    break;
}
}

any help would be great thanks

Switch statements don’t work with strings or chars, as was explained above in this thread. Your cases need to be 1, 2, 3, etc. not ‘1’, ‘2’, ‘3’, etc…

Thank You, reading an example and it was marked wrong.

Still saying it will not compile

@Ric, actually C++ will convert single quoted, single characters to their ascii decimal equivalents. So ‘1’ is the same as decimal 49, ‘2’ is 50, etc. However, ‘10’ being two quoted characters will NOT work.

Also, I noticed that there are lots of printf() commands which should be Serial.printf() if any output is to be generated.

2 Likes

What error are you getting? Also random(10) will produce numbers for 0-9, not 1-10.

1 Like

Thank You all fixed it.

Thanks, didn’t know that one. I knew that you could print a char with %d, and get the ASCII decimal equivalents, but I didn’t realize it did that conversion outside of something like printf.

@Ric, it’s not much different than using hex 0x31 in your code. The compiler knows to convert. :wink:

1 Like

I have a similar situation I’m trying to resolve a situation where older code with IF statements seems to not compile under the new compiler. I’m trying to get my head around the SWITCH statement (it seems to be an elegant alternative) but I’m not sure of what the ‘rules’ are.
Here’s the code snippet I’m trying to fix (the error was “control reaches end of non-void function [-Werror=return-type]” for each IF statement:

    int relayOn(String command){  // particle function for remotely turning on fuel filter
        if (command == "on" || command == "ON" || command == "On"){
            digitalWrite(relay, HIGH);
            return 1;
        }
    }
    
    int relayOff(String command){  // particle function for remotely turning off fuel filter
        if (command == "off" || command == "Off" || command == "OFF"){
            digitalWrite(relay, LOW);
            timerRunning = false;
            s = 0, m = 0, h = 0;  //  resets time to 00:00:00
            duration = s + (60 * m) + (3600 * h);
            fuelTotalMilliLitres  = 0;
            sendFuelFlowTotalToNextion();
            printTime();
            return 0;
        }
    }

I gather from the thread that I’m going to run into issues with the STRING command and will need to create an array of possible commands to use in the SWITCH CASE function like:

String cmdON[] = {"on", "ON", "On"}; //array of possible on commands
String cmdOFF[] = {"off", "OFF", "Off"}; //array of possible off commands

And can likely combine both IF statements into one SWITCH CASE function (elegant).

But I don’t grasp how to accomplish the same thing as an IF statement in the switch case.
Your help would be appreciated.

Switch statements can only work on ordinal/integral datatypes - so strings and even floating point numbers are no option - neither would be an array.

I think I see why your code wouldn’t compile but if you provided the error messages the compiler throws things could clear up pretty fast :wink:

BTW, since command is a String you can use all the fancy methods that class provides and for your case I’d suggest using String::equalsIgnoreCase() to catch all possible combinations of upper and lower case.
Alternatively you could force your incoming string into all-upper/all-lower case and compare against that only once.


here is why your code fails to compile

Your function signature indicates that your code will return an int but then it doesn’t in all cases. It only will when the if() condition is satisfied but fails to do so otherwise.
To rectify that just add a return -1 as last statement of the function(s).

1 Like