Counting chars in C on Mac OS X
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 the D
stays 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)
The program is working correctly: it's printing 6.
You see 6D because the terminal window printed ^D then went back to the beginning of the line, and your program prints 6 over the ^ leaving the following D. Try redirecting the output to a file, or giving it enough input that the answer has more than one digit, and you won't see the D.
The answer is 6 instead of 5 because of the newline, yes. If you don't want to count the newline at the end, subtract 1. If you don't want to count any newlines, subtract 1 whenever you see a newline.
精彩评论