简体   繁体   English

当C中的输入为0时,为什么我的getc()总是返回30?

[英]Why does my getc() always return 30 when input is 0 in C?

 int main(void){ char buffer[5] = {0}; int i; FILE *fp = fopen("haha.txt", "r"); if (fp == NULL) { perror("Failed to open file \\"mhaha\\""); return EXIT_FAILURE; } for (i = 0; i < 5; i++) { int rc = getc(fp); if (rc == EOF) { fputs("An error occurred while reading the file.\\n", stderr); return EXIT_FAILURE; } buffer[i] = rc; } fclose(fp); printf("The bytes read were... %x %x %x %x %x\\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]); return EXIT_SUCCESS; } 

I put eight 0s in my haha.txt file, and when I run this code it always gives me : 我在我的haha.txt文件中放了8个0,当我运行这个代码时它总是给我:

The bytes read were... 30 30 30 30 30 读取的字节是...... 30 30 30 30 30

Can someone tell me why? 有人可以告诉我为什么吗?

because '0' == 0x30 因为'0'== 0x30

The character '0' is the 0x30 (ascii). 字符“0”是0x30(ascii)。

'0' that you have entered in your text file is interpreted as char and not as an int . 您在文本文件中输入的'0'被解释为char而不是int Now, when you try to print that char in its hex (%x) value, the code just finds the equivalent of that char in hex and prints it. 现在,当您尝试在其hex (%x)值中打印该char时,代码只是以hex找到该char的等效值并打印它。

So, your '0' = 0x30 . 所以,你的'0' = 0x30 You can also try giving 'A' in your text file and printing it as hex, you will be getting '41' because 'A' = 0x41 . 您也可以尝试在文本文件中输入'A'并将其打印为十六进制,因为'A' = 0x41 ,您将获得'41'。 For your reference, the AsciiTable . 供您参考, AsciiTable

If you want to print out exactly what you have typed in your text file, then simply change your printf("The bytes read were... %x %x %x %x %x\\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]); 如果你想打印出你在文本文件中输入的确切内容,那么只需更改你的printf("The bytes read were... %x %x %x %x %x\\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]);

To

printf("The bytes read were... %c %c %c %c %c\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]); 
/* %c will tell the compiler to print the chars as char and not as hex values. */

You might want to read Format Specifiers and MSDN Link . 您可能需要阅读格式说明符MSDN链接

In your printf you use %x and this print in hex . 在你的printf你使用%x和这个hex打印。 The char '0' is equal to 48 in decimal so 0x30 in hex . char '0'等于48 in decimal所以0x30 in hex

To print 0 in char you need to use printf with %c 0 in char打印0 in char您需要使用带有%c printf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM