[英]C, why does printf add a "D" after a single digit long?
I'm working through the K&R C book and one of the example programs is this:我正在阅读 K&R C 书,其中一个示例程序是:
#include <stdio.h>
int main() {
long nc;
nc = 0;
while (getchar() != EOF) {
++nc;
}
printf("%ld", nc);
return 0;
}
When I run this program, it mostly behaves as I expect.当我运行这个程序时,它的行为大多符合我的预期。 So for an input like
This is a sentence
, it prints 19
.所以对于像
This is a sentence
这样的输入,它打印19
。
However, if I input anything under 10 characters (including EOF), there is a capital D
appended to the output number.但是,如果我输入少于 10 个字符(包括 EOF)的任何内容,则会在输出数字后附加一个大写
D
Eg for input hello
, the output is 6D
.例如,对于输入
hello
,输出是6D
。
Why is there a D
appended to an integer value and what does it mean?为什么有一个
D
附加到一个整数值,它是什么意思?
Note: This occurs with cc
, gcc
and clang
.注意:这发生在
cc
、 gcc
和clang
。
It turns out that D
is part of the ^D
that gets printed to the console when I input an EOF ( control
+ D
on Unix).事实证明,
D
是^D
一部分,当我输入 EOF(在 Unix 上为control
+ D
)时,它会打印到控制台。 Because there is no \\n
at the start of the printf
statement, a single-digit number will overwrite the ^
, while a double-digit number will overwrite the entire ^D
, which is what gave the impression of some weird behaviour.因为
printf
语句的开头没有\\n
,一位数将覆盖^
,而两位数将覆盖整个^D
,这给人的印象是一些奇怪的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.