I want to use switch-case in my program but the compiler gives me this error:
switch expression of type 'QString' is illegal   How can I use the switch statement with a QString?
My code is as follows:
bool isStopWord( QString word ) { bool flag = false ;  switch( word ) { case "the":     flag = true ;     break ; case "at" :     flag = true ;     break ; case "in" :     flag = true ;     break ; case "your":     flag = true ;     break ; case "near":     flag = true ;     break ; case "all":     flag = true ;     break ; case "this":     flag = true ;     break ; }  return flag ; } 
                1) The expression used in switch must be integral type ( int, char and enum). Any other type of expression is not allowed.
A switch statement—or simply a case statement—is a control flow mechanism that determines the execution of a program based on the value of a variable or an expression. Using a switch statement allows you to test multiple conditions and only execute a specific block if the condition is true.
You can use char 's for the switch expression and cases as well.
You can, creating an QStringList before iteration, like this:
QStringList myOptions; myOptions << "goLogin" << "goAway" << "goRegister";  /* goLogin = 0 goAway = 1 goRegister = 2 */   Then:
switch(myOptions.indexOf("goRegister")){   case 0:     // go to login...     break;    case 1:     // go away...     break;    case 2:     //Go to Register...     break;    default:     ...     break; } 
                        How can I use the switch statement with a QString?
You can't. In C++ language switch statement can only be used with integral or enum types. You can formally put an object of class type into a switch statement, but that simply means that the compiler will look for a user-defined conversion to convert it to integral or enum type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With