C 中 printf 输出中的附加“12”

Additional "12" in printf output in C

我编写了以下程序来了解 [=15=] 字符在 C 程序中的工作方式:

#include <stdio.h>

int main(void) {
    char a[] = {'1','2','[=10=]','2'};
    int i=0;
    for (i=0; i<4; i++){
        printf("%c\n",a[i]);
    }
    printf("%s",a);
    return 0;
}

好吧,没关系,我有以下输出:

sh-4.3$ gcc -o main *.c                                                                                          
sh-4.3$ main                                                                                                     
1                                                                                                                
2                                                                                                                

2

但是当我从 printf 命令中删除 \n 字符时,我在输出中收到一个额外的 12

//. Same as above
    for (i=0; i<4; i++){
        printf("%c",a[i]);
    }
//. Same as above

输出为:

12sh-4.3$ gcc -o main *.c                                                                                        
sh-4.3$ main 
12212

虽然我认为我必须看到这个 :

12sh-4.3$ gcc -o main *.c                                                                                        
sh-4.3$ main 
122

请注意,我使用this online compiler编译以上程序。这是 GNU GCC v4.8.3

您得到的额外 12 来自 printf("%s",a); 行:

  • 遍历循环打印出字符 12、null(无)和 2.
  • 打印出 a 处的字符串,直到出现空字符 ([=16=]),所以 12.

这就是为什么你得到输出 12212


使用换行打印会在不同的行上打印出 12、新行、212

在你的例子中你错过了最后的 12 因为你没有在末尾换行所以你的 shell 提示在它之后打印:注意你的问题你有 12sh-4.3$ 在其中一行的开头。