关于c ++:Operand类型不兼容(“ char”和“ const char *”)

Operand types are incompatible (“char” and “const char*”)

我收到以下错误...

Operand types are incompatible ("char" and"const char*")

...尝试执行if语句时。 我不确定我不确定是否可以将其转换为匹配类型,但我不理解输入值的存储方式?

要重现的示例代码是:

1
2
3
4
5
char userInput_Text[3];

if (userInput_Text[1] =="y") {
    // Do stuff.
}

我不确定是什么原因造成的。 似乎一种类型是char类型,另一种类型是const char指针,尽管我不确定是什么,作为参考,当我不使用数组时也会发生此错误。

和技巧/反馈将不胜感激。


双引号是C ++中C字符串的快捷语法。 如果要比较单个字符,则必须改用单引号。 您可以简单地将代码更改为此:

1
2
3
4
5
char userInput_Text[3];

if (userInput_Text[1] == 'y') { // <-- Single quotes here.
    // Do stuff.
}

以供参考:

  • "x" = const char *
  • 'x' = char