操作数类型不兼容(“char”和“const char*”)

时间:2020-12-26 19:17:55

I'm receiving the following error...

我收到如下错误……

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

操作数类型不兼容(“char”和“const char*”)

... when trying to perform an if statement. I'm assuming I'm not understanding how the input value is stored although I'm unsure if I can just cast it into the matching type?

…当尝试执行if语句时。我假设我不理解输入值是如何存储的,尽管我不确定是否可以将其转换为匹配类型?

Example code to reproduce is:

要复制的示例代码是:

char userInput_Text[3];

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

I'm not sure what's causing this. It would appear that one type is a char and the other is a const char pointer although I'm unsure of what, for reference this error also occurs when I'm not using an array).

我不知道是什么引起的。看起来,一种类型是char,另一种类型是const char指针,尽管我不确定是什么类型,作为参考,这个错误在我不使用数组时也会发生)。

And tips / feedback would be much appreciated.

非常感谢您的建议和反馈。

1 个解决方案

#1


21  

Double quotes are the shortcut syntax for a c-string in C++. If you want to compare a single character, you must use single quotes instead. You can simply change your code to this:

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

char userInput_Text[3];

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

For reference:

供参考:

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

#1


21  

Double quotes are the shortcut syntax for a c-string in C++. If you want to compare a single character, you must use single quotes instead. You can simply change your code to this:

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

char userInput_Text[3];

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

For reference:

供参考:

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