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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14544043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:26:02  来源:igfitidea点击:

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

c++carraystypes

提问by LeviTheDegu

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.

和提示/反馈将不胜感激。

回答by Karl Nicoll

Double quotes are the shortcut syntax for a c-stringin 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 字符串的快捷语法。如果要比较单个字符,则必须改用单引号。您可以简单地将代码更改为:

char userInput_Text[3];

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

For reference:

以供参考:

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