c如何将字符变量与字符串进行比较? [英] How does c compare character variable against string?
问题描述
以下代码在 C 中完全可以,但在 C++ 中则不行.在以下代码中,if
语句始终为 false.C如何比较字符变量和字符串?
The following code is completely ok in C but not in C++. In following code if
statement is always false. How C compares character variable against string?
int main()
{
char ch='a';
if(ch=="a")
printf("confusion");
return 0;
}
推荐答案
以下代码在C中完全没问题
不,完全没有.
在您的代码中
if(ch=="a")
本质上是试图将 ch
的值与字符串文字 "a"
的基地址进行比较.这是无意义和无用的.
is essentially trying to compare the value of ch
with the base address of the string literal "a"
,. This is meaning-and-use-less.
这里你想要的是使用单引号('
)来表示一个char
字面量,比如
What you want here, is to use single quotes ('
) to denote a char
literal, like
if(ch == 'a')
<小时>
注意 1:
详细说明char
字面量的单引号和字符串字面量的双引号的区别,
To elaborate on the difference between single quotes for char
literals and double quotes for string literal s,
对于 char
文字,C11
,章节 §6.4.4.4
For char
literal, C11
, chapter §6.4.4.4
整数字符常量是一个或多个用单引号括起来的多字节字符的序列,如 'x'
An integer character constant is a sequence of one or more multibyte characters enclosed in single-quotes, as in
'x'
对于字符串字面量,第 6.4.5 章
and, for string literal, chapter §6.4.5
字符串字面量是包含在双引号,如 "xyz"
.
Acharacter string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in
"xyz"
.
<小时>
注意 2:
也就是说,作为注释,main()
的推荐签名是 int main(void)
.
That said, as a note, the recommend signature of main()
is int main(void)
.
这篇关于c如何将字符变量与字符串进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!