Skip to main content
gamedev.net
🔒 Locked

Using switch with strings

Started by sipickles 2 replies 550+ views
Original Post
sipickles
sipickles
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
Conner McCloud
Conner McCloud
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
sipickles
sipickles
Thanks, I thought as much.

Oh well, no harm in asking!

Si

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.