AkThao
AkThao

Reputation: 643

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:

#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.

However, if I input anything under 10 characters (including EOF), there is a capital D appended to the output number.

E.g. for input hello, the output is 6D.

Why is there a D appended to an integer value and what does it mean?

Note: This occurs with cc, gcc and clang.

Upvotes: 2

Views: 252

Answers (2)

Angus
Angus

Reputation: 51

What version of gcc are you using? I ran the exact same code using gcc and it runs fine. Maybe it's an artifact left over by your terminal where it's trying to print the Ctrl-D for end of file

enter image description here

Upvotes: 0

AkThao
AkThao

Reputation: 643

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). 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.

Upvotes: 4

Related Questions