简体   繁体   English

C、为什么printf要在一位数长后加一个“D”?

[英]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 .注意:这发生在ccgccclang

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 ,这给人的印象是一些奇怪的行为。

What version of gcc are you using?你用的是什么版本的gcc? I ran the exact same code using gcc and it runs fine.我使用 gcc 运行了完全相同的代码,并且运行良好。 Maybe it's an artifact left over by your terminal where it's trying to print the Ctrl-D for end of file也许这是您的终端遗留的工件,它试图在文件末尾打印 Ctrl-D

在此处输入图片说明

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

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