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 us
This seems a little saner IMHO.
bool isStopWord( QString w ) {
return (
w == "the" ||
w == "at" ||
w == "in" ||
w == "your" ||
w == "near" ||
w == "all" ||
w == "this"
);
}
This has nothing to do with Qt, just as it has nothing to do with the colour of your socks.
C++ switch syntax is as follows:
char c = getc();
switch( c ) {
case 'a':
a();
break;
case 'b':
b();
break;
default:
neither();
}
If that doesn't help then please list in detail the error message, possible along with the colour of you socks.
Edit: to respond to your reply, you can't use switch
with none-integral types. In particular, you can't use class types. Not objects of type QString
and not objects of any other type. You can use an if-else if-else
construct instead, or you can use runtime or compile time polymorphism, or overloading, or any of the array of alternatives to a switch
.
It is identical to a C++ switch statement.
switch(var){
case(option1):
doesStuff();
break;
case(option2):
etc();
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.
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;
}
I would suggest to use if and break. This would make it near to switch case in the computation.
QString a="one"
if (a.contains("one"))
{
break;
}
if (a.contains("two"))
{
break;
}