QString in switch statement
-
wrote on 21 Jul 2016, 14:34 last edited by
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.
-
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.
-
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.
wrote on 21 Jul 2016, 17:03 last edited by beeckscheWhen 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.
-
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. -
wrote on 21 Jul 2016, 19:31 last edited by
Just use
if (str == "...") { // ... } else if (str == "...") { // ... } //... else { // ... }
1/5