c如何比较字符变量和字符串? [英] How does c compare character variable against string?
问题描述
以下代码在C中完全正确,但不在C ++中。在下面的代码如果
语句总是false。如何比较字符变量和字符串?
int main()
{
char ch ='a ';
if(ch ==a)
printf(confusion);
return 0;
}
以下代码在C中完全正确
> if(ch ==a)
实际上是试图比较 ch
与字符串文字的基地址a
,。这是无意义的。
你想要的是使用单引号('
)表示 char
文字,例如
if 'a')
注意1:
要详细说明 char
文字的单引号与字符串字面值
对于 char
文字, C11
章节§6.4.4.4
整数字符常量是一个包含在单引号中的一个或多个多字节字符的序列,如
'x'
和字符串章节§6.4.5
字符串字面值是一个零或多个多字节字符序列,包含在
双引号,如xyz
。
注意2:
也就是说,作为注释,推荐签名 main ()
是 int main(void)
。
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;
}
The following code is completely ok in C
No, Not at all.
In your code
if(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.
What you want here, is to use single quotes ('
) to denote a char
literal, like
if(ch == 'a')
NOTE 1:
To elaborate on the difference between single quotes for char
literals and double quotes for string literal s,
For char
literal, C11
, chapter §6.4.4.4
An integer character constant is a sequence of one or more multibyte characters enclosed in single-quotes, as in
'x'
and, for string literal, chapter §6.4.5
Acharacter string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in
"xyz"
.
NOTE 2:
That said, as a note, the recommend signature of main()
is int main(void)
.
这篇关于c如何比较字符变量和字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!