Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch/case statement in C++ with a QString type

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 ; } 
like image 547
amiref Avatar asked Mar 27 '11 20:03

amiref


People also ask

Can I pass any type of variable to a switch statement in C?

1) The expression used in switch must be integral type ( int, char and enum). Any other type of expression is not allowed.

Can Switch case have multiple conditions in C?

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.

Can characters be used in switch case in C?

You can use char 's for the switch expression and cases as well.


2 Answers

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; } 
like image 112
Lauro Oliveira Avatar answered Sep 22 '22 09:09

Lauro Oliveira


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.

like image 38
AnT Avatar answered Sep 21 '22 09:09

AnT