This question already has an answer here:
这个问题在这里已有答案:
- Why the switch statement cannot be applied on strings? 18 answers
- 为什么switch语句不能应用于字符串? 18个答案
I'm getting the error "Expression must have integral or enum type" on the switch
statement of my (incomplete) function below. I've stared at it for a while and can't figure out what the matter is. Any insight greatly appreciated.
我在下面的(不完整)函数的switch语句中得到错误“Expression必须具有整数或枚举类型”。我已经盯着它看了一会儿,无法弄清楚是怎么回事。任何见解都非常感激。
std::string CWDriver::eval_input(std::string expr)
{
std::vector<std::string> params(split_string(expr, " "));
std::string output("");
if (params.size() == 0)
{
output = "Input cannot be empty.\n";
}
else
{
switch (params[0])
{
case "d":
}
}
}
2 个解决方案
#1
2
The error is clear. You can only use integral types (integer
, enum
, char
etc. which are convertible to integral
value), or any expression that evaluates to an integral type in switch
statement.
错误很明显。您只能使用整数类型(整数,枚举,字符等可转换为整数值),或任何在switch语句中求值为整数类型的表达式。
#2
1
params[0]
has type of std::string
. You can't use std::string
type (which is not integral) as a switch
parameter. If you are confident strings are not empty use switch (param[0][0])
and case 'd'
. But in this case you will be able to switch over one-character strings only. If you need to switch over longer strings you need to use the sequence of if-else if-else if-...
.
params [0]具有std :: string类型。您不能将std :: string类型(不是整数)用作switch参数。如果您确信字符串不为空,请使用switch(param [0] [0])和case“d”。但在这种情况下,您只能切换一个字符的字符串。如果你需要切换更长的字符串,你需要使用if-else的序列if-else if -....
#1
2
The error is clear. You can only use integral types (integer
, enum
, char
etc. which are convertible to integral
value), or any expression that evaluates to an integral type in switch
statement.
错误很明显。您只能使用整数类型(整数,枚举,字符等可转换为整数值),或任何在switch语句中求值为整数类型的表达式。
#2
1
params[0]
has type of std::string
. You can't use std::string
type (which is not integral) as a switch
parameter. If you are confident strings are not empty use switch (param[0][0])
and case 'd'
. But in this case you will be able to switch over one-character strings only. If you need to switch over longer strings you need to use the sequence of if-else if-else if-...
.
params [0]具有std :: string类型。您不能将std :: string类型(不是整数)用作switch参数。如果您确信字符串不为空,请使用switch(param [0] [0])和case“d”。但在这种情况下,您只能切换一个字符的字符串。如果你需要切换更长的字符串,你需要使用if-else的序列if-else if -....