c++ – error: switch quantity not an integer
c++ – error: switch quantity not an integer
In switch
, the expression must be of an integral type or of a class type for which there is an unambiguous conversion to integral type (quoting VS2008 docs).
A string class doesnt have unambiguous conversion to integral type, like a char
does.
As a work-around:
-
Create a
map<string, int>
and switch on the value of the map:switch(command_map[command])
` -
Do a set of
if
/else
instead of switch. Much more annoying and hard to read, so Id recommend the map route.
As an aside, an even better solution for really complicated logic like that is to improve the mapping solution to get rid of switch
completely and instead go with a function lookup: std::map<std::string, functionPointerType>
. It may not be needed for your specific case, but is MUCH faster for complicated very long look-up logic.
As others and the compiler commented, strings are not allowed with switch
. I would just use if
bool Calculator::is_legal_command() const {
if(command == TAN) return true;
if(command == SIN) return true;
if(command == COS) return true;
if(command == LOG) return true;
if(command == LOG10) return true;
return false;
}
I dont think thats any more complicated, and its about as fast as it could get. You could also use my switch macro, making it look like
bool Calculator::is_legal_command() const {
sswitch(command)
{
scase (TAN):
scase (SIN):
scase (COS):
scase (LOG):
scase (LOG10):
return true;
sdefault():
return false;
}
}
(having break
after a return
is dead code, and so should be avoided).
c++ – error: switch quantity not an integer
Strings cannot be used in switch statements in C++. Youll need to turn this into if
/else if
, like this:
if (command == tan)
{
// ...
}
else if (command == cos)
{
// ...
}
// ...