switch case mit string nicht möglich?
-
Ja kann man mit switch case nicht auf strings prüfen? Nur auf Zahlen/Konstante.
-
Hallo
Ja kann man mit switch case nicht auf strings prüfen?
Nein, kann man nicht.
Nur auf Zahlen/Konstante.
Ja, nur auf integrale Typen.
bis bald
akari
-
std::map :xmas1:
-
Hi!
Wie schon gesagt kann man mit std::map arbeiten. Ich würd nicht unbedingt sagen das es gut oder die beste Lösung ist, aber sie funktioniert. Habe hier mal ein Beispiel wie das aussehen könne:
#include <iostream> #include <string> #include <map> using namespace std; typedef void (*STRING_CASE)(); void a_str() { cout << "Your choice: String A" << endl; } void b_str() { cout << "Your choice: String B" << endl; } int main(int argc, char *argv[]) { map<string, STRING_CASE> m; m["A_String"] = a_str; m["B_String"] = b_str; string s; cin >> s; map<string, STRING_CASE>::iterator it = m.find(s); if(it != m.end()) (*it->second)(); else cerr << "String not found." << endl; }
Greetz
-
und wenn's unbedingt mit switch/case sein soll...
#include <string> #include <iostream> using namespace std; int main() { string mystrings[] = {"hallo","doof","c++"}; repeat: string in; cin >> in; // string to number int idx; for (idx=0; idx<sizeof(mystrings)/sizeof(string); idx++) if (in == mystrings[idx]) break; switch (idx) { case 0: // hallo cout << "found 1" << endl; break; case 1: // doof cout << "found 2" << endl; break; case 2: // c++ cout << "found 3" << endl; break; default: // leider nix cout << "nothing found" << endl; break; } goto repeat; // alles nochmal }
-
imro schrieb:
Ja kann man mit switch case nicht auf strings prüfen? Nur auf Zahlen/Konstante.
switch kann nur mit Variablen eines ordinalen Typs etwas anfangen. Für Strings umgeht man das einfach mit if/else
if (blub == "string1") //... else if (blub == "string2") //... else if (blub == "string3") //... else //...