簡體   English   中英

在C的中間打印帶空字符的char數組

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

我注意到當您嘗試在C中打印一個空字符時,將不會打印任何內容。

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

但是,我正在嘗試一個接一個地打印以下數組中的字符,直到第六個字符(即空字符)為止。

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

我期望打印“ Hello”,因為第六個字符為null,因此不會打印任何內容。 但是我的輸出是:“ HelloB”。 似乎printf跳過了空字符,而只是轉到下一個字符。 我不確定為什么輸出是“ HelloB”而不是“ Hello”。

任何見解將不勝感激。

結構'\\0'通常用於表示空字符。 這里

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

它什么也不打印。

並在s

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

當你打印像

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

printf()最多打印0<7(h)1<7(e) .. 5<7(nothing on console)6<7(B)迭代,並且6th字符是B因此它打印HelloB

我期望打印“ Hello”? 為此,您應該循環旋轉直到遇到\\0 例如

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

甚至不需要檢查s[i] != '\\0'

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

您可以使用以下兩個選項
1. size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
2.遍歷每個字符並打印。

int i; for(i=0; i<7; i++) int i; for(i=0; i<7; i++)生成7次,而不是6次迭代。 打印\\0不會在控制台上生成任何像素(字符6),然后在第7個字符( B )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM