I am running an example from The C Programming Language by Kernighan and Ritchie.
#include <stdio.h>
main() {
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
I’m on Mac OS X, so I compile it, run it, type in "12345", press enter for newline (I believe newline is the sixth character?) and then press ctrl-D to send an EOF.
It prints out "6D".
Why is the "D" there?
How do I write a program to just count the 5 chars in "12345" and not the newline?
Should I just subtract one at the end?
How do I get it to stop printing the "D"?
What happens is that the terminal actually echoes your control-D (and prints it out as
^D) when you type it, but then your program overwrites that line with a number and a line-feed. So your one-digit number overwrites the^, but theDstays there.If you enter more than 10 characters, or if change the code by adding a space at the end of your format string (
"%ld \n"), then your program would overwrite the^D(though it would still have been echoed by your terminal)