[英]simple question on C
I have this snippet of the code 我有这段代码
char *str = “123”;
if(str[0] == 1) printf("Hello\n");
why I can't receive my Hello
thanks in advance! 为什么我无法提前收到
Hello
谢谢! how exactly compiler does this comparison if(str[0] == 1)
? if(str[0] == 1)
编译器如何进行比较?
You want to do this: 您想这样做:
if (str[0] == '1') ...
The difference is that you are comparing str[0]
to the number 1, while my code above is comparing str[0]
to the character '1'
(which has ASCII value 49). 区别在于您将
str[0]
与数字 1进行比较,而我上面的代码将str[0]
与字符 '1'
(具有ASCII值49)进行比较。 Not all programming languages treat characters and numbers interchangeably in this way, but C does. 并非所有的编程语言都以这种方式互换使用字符和数字,但是C可以。
Check out ASCII for more information about how computers map numbers to characters. 请查看ASCII ,以获取有关计算机如何将数字映射为字符的更多信息。
First the right way is to do this: 首先正确的方法是这样做:
if(str[0] == '1')
Or : 要么 :
if(str[0] == 49)
Second, you must take care of the difference between 1
and '1'
其次,您必须注意
1
与'1'
之间的差异
Which means: ('1'==1)
is false !! 这意味着:(
('1'==1)
是错误的!
However ('1'==49)
is true !! 但是
('1'==49)
是正确的!
When you write '1'
in C/C++ it -automatically- be translated to the corresponding ASCII 49
, that is how '1'
is actually represented in C/C++ 当您在C / C ++中写入
'1'
,它会自动翻译为相应的ASCII 49
,这就是在C / C ++中实际表示'1'
方式
This is because you are comparing the first character of str
to the number 1. The actual character code of '1'
is 49. So, either of these will work: 这是因为您正在将
str
的第一个字符与数字1进行比较。实际的字符代码'1'
为49。因此,以下两种方法均可使用:
if (str[0] == '1')
if (str[0] == 49)
Remember that 1
isn't the same as '1'
. 请记住,
1
与'1'
。 The first one is a number, the second one is a character. 第一个是数字,第二个是字符。 If you want to learn more about this, you should probably look here: http://en.wikipedia.org/wiki/Character_encoding
如果您想了解更多有关此的信息,则可能应该在这里查看: http : //en.wikipedia.org/wiki/Character_encoding
*str is a pointer type char var...that store the base address of string .str[0] holds the first char ...that is 1 and also it is a char ..so,i it is denoted with is '1'... * str是一个指针类型char var ...,它存储字符串的基地址.str [0]保留第一个char ...,即1,并且也是char ..so,i表示为' 1'...
try this : 尝试这个 :
if(str[0] == '1')
printf("Hello \n");
您正在将一个char与一个int进行比较,应该是
if(str[0] == '1')
you need to ask 你需要问
*str = “123”; * str =“ 123”; if(str[0] == '1') printf("Hello\\n");
if(str [0] =='1')printf(“ Hello \\ n”);
See those single quotes around 1? 看到那些单引号在1附近吗? You ned to compare a character and you are comparing an integer.
您需要比较一个字符,而您要比较一个整数。
尝试使用if(str[0] == '1')
而不是与1
进行比较,这在C中是1和true :)
use this ==> 使用这个==>
if(str[0] == '1')
printf("Hello \n");
try this one ..... 试试这个.....
if(str[0] == '1')
printf("Hello \n");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.