[英]Additional “12” in printf output in C
I wrote the following program to learn how \\0
character works in C programs: 我编写了以下程序,以了解\\0
字符在C程序中的工作方式:
#include <stdio.h>
int main(void) {
char a[] = {'1','2','\0','2'};
int i=0;
for (i=0; i<4; i++){
printf("%c\n",a[i]);
}
printf("%s",a);
return 0;
}
Well, that's okay and I have the following output : 好吧,没关系,我有以下输出:
sh-4.3$ gcc -o main *.c
sh-4.3$ main
1
2
2
But when I remove \\n
character from printf
command, I receive one additional 12
in output: 但是,当我从printf
命令中删除\\n
字符时,我在输出中又收到一个12
:
//. Same as above
for (i=0; i<4; i++){
printf("%c",a[i]);
}
//. Same as above
Output is: 输出为:
12sh-4.3$ gcc -o main *.c
sh-4.3$ main
12212
While I think I must see this : 虽然我认为我必须看到这一点:
12sh-4.3$ gcc -o main *.c
sh-4.3$ main
122
Note that I used this online compiler to compile above programs. 请注意,我使用此在线编译器来编译上述程序。 It's GNU GCC v4.8.3 这是GNU GCC v4.8.3
The extra 12
you are getting is from the printf("%s",a);
您获得的额外12
来自printf("%s",a);
line: 线:
1
, 2
, null (nothing), and 2
. 通过循环迭代打印出人物1
, 2
,空(无),和2
。 a
prints up until the null character ( \\0
), so 12
. 在打印出字符串a
打印直到空字符( \\0
),因此12
。 That's why you get the output 12212
. 这就是为什么获得输出12212
的原因。
Printing with the newlines prints out 1
, 2
, new line, 2
, and 12
on separate lines. 与换行打印出打印1
, 2
,新的行, 2
,和12
在不同的行。
In your example you are missing the final 12
because you don't have new line at the end so your shell prompt gets printed after it: notice in your question that you have 12sh-4.3$
at the beginning of one of the lines. 在您的示例中,您错过了最后12
行,因为末尾没有新行,因此您的shell提示符将在其后打印:请注意您的问题中,其中12sh-4.3$
的开头有12sh-4.3$
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.