Using switch with strings

Started by
2 comments, last by sipickles 18 years ago
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
Advertisement
Not in C or C++. You're stuck using if/else or string/functor [hash]maps.

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
Thanks, I thought as much.

Oh well, no harm in asking!

Si

This topic is closed to new replies.

Advertisement