简体   繁体   English

在C的中间打印带空字符的char数组

[英]Printing char array with null character in the middle in C

I have noticed that when you try to print a null character in C, nothing will get printed. 我注意到当您尝试在C中打印一个空字符时,将不会打印任何内容。

printf("trying to print null\n");
printf("%c", '\0');

However, I am trying to print the characters in the following array one by one, up to the sixth character which is the null character. 但是,我正在尝试一个接一个地打印以下数组中的字符,直到第六个字符(即空字符)为止。

char s[] = "Hello\0Bye";
int i;
for(i = 0; i < 7; i++) {
    printf("%c", s[i]);
}
printf("\n");

I was expecting "Hello" to be printed, as since the sixth character is null nothing will be printed. 我期望打印“ Hello”,因为第六个字符为null,因此不会打印任何内容。 However my output was: "HelloB". 但是我的输出是:“ HelloB”。 It seems like printf skipped the null character and just went to the next character. 似乎printf跳过了空字符,而只是转到下一个字符。 I am not sure why the output is "HelloB" instead of "Hello". 我不确定为什么输出是“ HelloB”而不是“ Hello”。

Any insights would be really appreciated. 任何见解将不胜感激。

The construction '\\0' is commonly used to represent the null character. 结构'\\0'通常用于表示空字符。 Here 这里

printf("%c", '\0');

it prints nothing. 它什么也不打印。

And in the decalaration of s 并在s

char s[] = "Hello\0Bye"; 

when you print like 当你打印像

for(i = 0; i < 7; i++) {
    printf("%c", s[i]); 
}

printf() prints upto 0<7(h) , 1<7(e) .. 5<7(nothing on console) , 6<7(B) iterations only and 6th charactar is B hence its prints HelloB . printf()最多打印0<7(h)1<7(e) .. 5<7(nothing on console)6<7(B)迭代,并且6th字符是B因此它打印HelloB

I was expecting "Hello" to be printed ? 我期望打印“ Hello”? For that you should rotate loop until \\0 encountered. 为此,您应该循环旋转直到遇到\\0 For eg 例如

for(i = 0; s[i] != '\0'; i++) { /* rotate upto \0 not 7 or random no of times */ 
   printf("%c", s[i]); 
}

Or even you no need to check s[i] != '\\0' 甚至不需要检查s[i] != '\\0'

for(i = 0; s[i]; i++) { /* loop terminates automatically when \0 encounters */ 
     printf("%c", s[i]); 
}

You can use below two options 您可以使用以下两个选项
1. size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); 1. size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
2.Iterate through each character and print it. 2.遍历每个字符并打印。

int i; for(i=0; i<7; i++) int i; for(i=0; i<7; i++) generates 7, not 6 iterations. int i; for(i=0; i<7; i++)生成7次,而不是6次迭代。 Printing \\0 generates no pixels on the console (character 6) and then the 7th character ( B follows). 打印\\0不会在控制台上生成任何像素(字符6),然后在第7个字符( B )。

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

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