how can i use a string in a switch statement?

how can i use a string in a switch statement?

You can't. You can only switch on "integral types" like char and int.

You need to do a bunch of if-else if statements for strings.

thanks for your help

You can also define a map<string,int> that you can use to look up a string, obtain a corresponding integer, and use that integer in a switch. Depending on how you write your code, that strategy may well run faster, and be easier to maintain, than using a series of if-then-else statements.

Since I don't know exactly what your situation is, I'm just going to throw this out there as a possibility.

You could also use an enumeration:

#include <iostream>
using namespace std;

enum myEnum {BASE_VAL = 0, FIRST_VALUE, SECOND_VALUE, VALUE_TEN = 10};

int main() {
  myEnum example(FIRST_VALUE);   //select any valid member of the enumeration

  switch (example) {
    case BASE_VAL:
      cout << "example is a BASE_VAL." << endl;
      break;
    case FIRST_VALUE:
      cout << "example is a FIRST_VALUE." << endl;
      break;
    case SECOND_VALUE:
      cout << "example is a SECOND_VALUE." << endl;
      break;
    case VALUE_TEN:
      cout << "example is VALUE_TEN." << endl;
    default:
      cout << "example is not a valid member of myEnum." << endl;
  }
  cin.get();
  return 0;
}

An enumeration is essentially just a collection of integral constants. That's why it works.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.