Character Counting in C on Mac OS X

Straight from K & R, I have

#include <stdio.h>

main() {
    long nc;
    nc = 0;
    while (getchar() != EOF)
        ++nc;
    printf("%ld\n", nc);
}

I am on Mac OS X, so I compile it, run it, type “12345”, press enter for a new line (this is the sixth char I think), and then press ctrl-D to send EOF.

Thing prints "6D". Why is there D? How to write a program to simply count 5 characters in "12345" and not on a new line? Should I just subtract it at the end? How can I make him stop printing D?

+3
source share
2 answers

, , -D ( ^D) , . , ^, D .

10 , ("%ld \n"), ^D ( )

+9

: 6.

6D, , ^ D, , 6 ^, D. , , D.

: 6 5 - , . , 1. - , 1 , .

+1

Source: https://habr.com/ru/post/1785013/


All Articles