Mail Archives: djgpp/2003/12/01/11:00:32
cmad_x AT yahoo DOT com (Chris Mantoulidis) wrote:
> in my c++ program i use the switch statement with a string parameter.
> for example
>
> string s;
> cin >> s;
> switch (s)
> {
> .......
> }
>
> but i get an error saying "switch quantity not an integer"... probably
> the switch needs an integer parameter and probably that's the same
> with C (and a char * in the example).
True enough.
> so... there is no way that i can use switch for a string?
>
> i have to use IF-ELSE???
No, assuming you are using C++ (rather than "C/C++", whatever that
is), you don't have to use if-else if you don't want to. You could
use a std::map, for example. If you're wedded to using a switch
statement, you could do something like the following:
#include <map>
#include <string>
#include <iostream>
int main()
{
using namespace std;
enum CommandNums { Error = 0, Stop, Go, Reset, Quit };
map<string, int> commands;
commands["stop"] = Stop;
commands["go"] = Go;
commands["reset"] = Reset;
commands["quit"] = Quit;
bool keepGoing = true;
while (keepGoing) {
cout << "Enter your command, quit to end: ";
string s;
cin >> s;
switch (commands[s]) {
case Stop:
cout << "You entered 'stop'" << endl;
break;
case Go:
cout << "You entered 'go'" << endl;
break;
case Reset:
cout << "You entered 'reset'" << endl ;
break;
case Quit:
cout << "Goodbye" << endl;
keepGoing = false;
break;
case Error:
cout << "I didn't understand that." << endl;
}
}
}
A more sophisticated way would be to ditch the switch statement
altogether and instead map each command to a function pointer or
functor that would execute the code corresponding to the command.
Again, you're likely to get more helpful info posting to
comp.lang.c++.moderated or comp.lang.c++ than posting here.
Best regards,
Tom
- Raw text -