Unsolved QString in switch statement
-
Can't we use QString for comparision in switch statement like below,
QString str = "TEMP";
switch (str) {
I tried to use like this but it didnot work.
-
@ankit-thakar
No, C++ doesn't allow for non-integral types in switch statements.Kind regards.
-
When you want to use a String in a switch statement, you obviosily know which String can be entered. In this case you can use enums.
enum Strings { String1, String2, etc. }
With this enums you're allowed to use the switch statement. Like
Strings myString; switch (myString) { case Strings::String1: break; case Strings::String2: break; ... default: break; }
So you can use the switch and it is readable in your code.
-
@beecksche
The inefficient part would be converting the string you have to a corresponding enum, and this pretty much defeats the whole purpose of having a duplicating enum and aswitch
construct. -
Just use
if (str == "...") { // ... } else if (str == "...") { // ... } //... else { // ... }