gpt4 book ai didi

c - c 如何将字符变量与字符串进行比较?

转载 作者:行者123 更新时间:2023-12-03 22:50:38 24 4
gpt4 key购买 nike

下面的代码在 C 中完全可以,但在 C++ 中则不行。在以下代码中 if声明总是错误的。 C 如何将字符变量与字符串进行比较?

int main()
{
char ch='a';
if(ch=="a")
printf("confusion");
return 0;
}

最佳答案

The following code is completely ok in C



一点都不。

在你的代码中
  if(ch=="a")

本质上是试图比较 ch 的值与字符串文字的基地址 "a" ,。这是无意义和无用的。

您在这里想要的是使用单引号( ' )来表示 char字面意思,比如
  if(ch == 'a')

注 1:

详细说明 char单引号的区别字符串文字的文字和双引号,

对于 char文字, C11 ,第 6.4.4.4 章

An integer character constant is a sequence of one or more multibyte characters enclosed in single-quotes, as in 'x'



并且,对于字符串文字,第 6.4.5 章

Acharacter string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in "xyz".



注 2:

也就是说,作为注释, main() 的推荐签名是 int main(void) .

关于c - c 如何将字符变量与字符串进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31406415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com