Why this doesn't work for string?Code:string x = "test1";
switch(x){
case "test1" : break;
case "test2" : break;
default : break;
}
Printable View
Why this doesn't work for string?Code:string x = "test1";
switch(x){
case "test1" : break;
case "test2" : break;
default : break;
}
Because switch only uses integer constants, and "test1" is not an integer constant.
but switch can also base on char, not only an integer
That's because char is an integer.
Edit: and by that I mean, that is an "integral type" -- the integral types are char, short, int, long, long long, and their unsigned counterparts. All of these are integers, as stored in memory.
as well as enum
If the strings you want to switch on are part of a set, you could create an enum of the same set, then create a StringToEnum() function which converts the string you pass to it into an enum. Then you can just do your switch on the enum.
You can map strings to enumerations to alleviate your issue and also provide a common place where the string literals are defined.
Header
SourceCode:
enum TestStringIDs
{
TEST_ID1,
TEST_ID2,
END_OF_IDs
}
struct StringToID
{
TestStringIDs ID;
std::string Text;
}
This is great for mapping string literals to enumerations and can easily be loaded from a config file later. One string compare can be done within a loop and then the ID can be retrieved or vice versa. StringToID::END_OF_IDs is so that you can iterate the enumeration from 0 to END_OF_IDs.Code:
StringToID StringToIDBridge [] = {
{TEST_ID1,"Test string 1"},
{TEST_ID2,"Test string 2"} };
Just food for thought.