Jump to content
  • Advertisement
Sign in to follow this  
sipickles

Using switch with strings

This topic is 4514 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I am building a GUI in directX, and using some simple text initialisation files to build the GUI at startup. I wondered if it was possible to do something similar to a switch statement, but with strings? for instance fscanf( pFile, "%s", typeStr ); switch ( typeStr ) { case "button": // etc } At the moment, the compiler says switch expression of type 'std::string' is illegal Same thing with char arrays. As a result I am using a number instead of the string, but its not very friendly. I knwo I could use this: #define BUTTON 0 fscanf( pFile, "%d", type ); switch ( type ) { case BUTTON: // etc } but its still a zero in the txt file, not a string! Any advice gratefully received! Thanks Simon

Share this post


Link to post
Share on other sites
Advertisement
The only solution, in C/C++, is to create a function that maps strings to integers in some way.

int maping(const std::string& str)
{
if(str == "one") return 1;
if(str == "two") return 2;
if(str == "three") return 3;
return 0;
}

int main()
{
switch(maping("two")) {
case 1: cout << "one" << endl; break;
case 2: cout << "two" << endl; break;
case 3: cout << "three" << endl; break;
default: cout << "default" << endl; break;
}
}

CM

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!