Can you switch on a string in C++?
Not directly. A switch statement in C++ accepts integer types and enumeration types, and std::string is neither. If you write switch (command) with a string variable, the compiler rejects it. The case labels have the same problem: case "start": is not valid, because a case label has to be a constant integer value.
You can still branch on text. The usual options are an if chain that compares strings with ==, a lookup that turns the string into an enum value, or a switch on a single character from the string. The sections below cover each one.
Why switch needs an integer
A switch case statement in C++ jumps straight to the label that matches a value. To do that, the value has to be something the compiler can compare against constant labels, such as an int, a char, or an enum. A std::string holds a sequence of characters with a length that can change, so it has no single value to match against.
Option 1: use an if else chain
Comparing a std::string with == checks whether the two strings hold the same text. This is the simplest way to branch on text:
#include <iostream>
#include <string>
int main() {
std::string command = "start";
if (command == "start") {
std::cout << "Starting...\n";
} else if (command == "stop") {
std::cout << "Stopping...\n";
} else {
std::cout << "Unknown command\n";
}
}
This reads well for a few options. With many options, the chain gets long, and that is when the enum approach below helps.
Option 2: map the string to an enum, then switch
Once the text becomes an enum value, a switch works. A lookup table does the string part, and the switch does the branching:
#include <iostream>
#include <string>
#include <unordered_map>
enum class Command { Start, Stop, Unknown };
Command parseCommand(const std::string& text) {
static const std::unordered_map<std::string, Command> commands = {
{"start", Command::Start},
{"stop", Command::Stop},
};
auto it = commands.find(text);
if (it == commands.end()) {
return Command::Unknown;
}
return it->second;
}
int main() {
switch (parseCommand("stop")) {
case Command::Start:
std::cout << "Starting...\n";
break;
case Command::Stop:
std::cout << "Stopping...\n";
break;
case Command::Unknown:
std::cout << "Unknown command\n";
break;
}
}
Each case label is a named enum value, which is a constant, so the compiler accepts it. The static map is built the first time the function runs and reused after that. A std::map works the same way if you prefer an ordered container.
Giving unknown input its own enum value means the switch lists every outcome. If you later add a new enum value and forget to handle it in the switch, the compiler can warn you when you compile with -Wall.
Option 3: switch on one character
If the first letter decides the choice, you can switch on a char:
std::string choice = "y";
if (!choice.empty()) {
switch (choice[0]) {
case 'y':
case 'Y':
std::cout << "Yes\n";
break;
default:
std::cout << "No\n";
break;
}
}
Check that the string is not empty before you look at its first character. This approach only sees one character, so "yes" and "yellow" both match 'y'. Use it only when that is what you want.
The C version: use strcmp instead of ==
In C, a string is a char array, and == compares the addresses of two arrays, not their text. The result depends on where the arrays are stored, so it is not a text comparison. Use strcmp() from <string.h> instead. It returns 0 when two strings match:
#include <stdio.h>
#include <string.h>
int main(void) {
const char *command = "start";
if (strcmp(command, "start") == 0) {
printf("Starting...\n");
} else if (strcmp(command, "stop") == 0) {
printf("Stopping...\n");
} else {
printf("Unknown command\n");
}
return 0;
}
The enum approach also works in C with a plain enum and strcmp() doing the lookup. Because the same comparison pitfall applies to every text comparison in C, it helps to know how to compare two strings in C before you write a larger program.
Common mistakes
- Quoted case labels.
case "start":does not compile. Use an enum or anifchain instead. - Missing break. Without a
breakin each case, execution continues into the next case. The break statement in C++ is what ends each branch. - Using == on char pointers. In C, and in C++ with
const char *,==compares addresses, not text. - No unknown case. Input that matches nothing should go to a
defaultlabel or an unknown value, so it is not ignored by accident.
Which approach to pick
- A few fixed options: use an
if elsechain with==. - Many fixed options with clear names: map the string to an enum, then switch on the enum.
- The first letter decides the choice: switch on a
charafter an empty check. - Writing C: use
strcmp()in anifchain, or map to an enum withstrcmp()doing the lookup.
Text cannot go directly into a switch, but a small lookup turns it into a value the switch can handle, and the rest of the code stays clean.