X-Authentication-Warning: delorie.com: mail set sender to djgpp-bounces using -f From: Thomas8675309 AT yahoo DOT com (Tom) Newsgroups: comp.os.msdos.djgpp Subject: Re: C/C++ switch statement question Date: 1 Dec 2003 07:59:08 -0800 Organization: http://groups.google.com Lines: 75 Message-ID: <7b68d58f.0312010759.43e92543@posting.google.com> References: NNTP-Posting-Host: 63.72.148.162 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 8bit X-Trace: posting.google.com 1070294348 8716 127.0.0.1 (1 Dec 2003 15:59:08 GMT) X-Complaints-To: groups-abuse AT google DOT com NNTP-Posting-Date: Mon, 1 Dec 2003 15:59:08 +0000 (UTC) To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com 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 #include #include int main() { using namespace std; enum CommandNums { Error = 0, Stop, Go, Reset, Quit }; map 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