Solved K & R book question

I am doing the char count sample program.

Code:
#include<stdio.h>
main()
{
double nc;
     for (nc = 0; getchar() != EOF; ++nc)
          ;
     printf("%.0f\n",nc);
}

When I do ctrl-d to end the program it returns the number of characters including a D after it. Is this normal? I am on freebsd 9.1 using cc.
 
The D you are seeing is most likely the D left over after the ctrl-d is echoed as ^D, followed by the cursor being moved to the left-most position on that same line, and then the (I'm guessing) single digit of characters counted is printed.

Try typing in more than 10 characters and I think you'll see the D get overwritten...
 
If at all possible, try to seek out a book on at least C89. K&R C is obsolete and some recent C/C++ compilers won't even compile it.
 
There are issues with it regarding compatibility but I have never found a better written book and would still recommend it and let one stumble but find the answers to the problems than suggest almost anything else only 200 pages long.
 
Back
Top