I am reading PrenticeHall. The C Programming Language – 2nd Ed.Kernighan,Ritchie.
In this book(pg-20) an example of a program is given which is supposed to print the number of characters that user types in the console window, and here is its code .
#include <stdio.h>
main()
{
double nc;
for (nc = 0; getchar() != EOF; ++nc)
;
printf("%.0f\n", nc);
}
But when I run this , and type something in the console, it wont print anything at all, the cursor would keep on blinking .
and this is exactly the way code is written in that book.
I have tried it another way also, but this also didn’t work out, same result as that previous code.
#include <stdio.h>
main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
any ideas to how to make this thing work ?
P.S.
I am using windows OS. (still)
The reason is that the code tries to read all the input until the end of file. If this program was reading from a file, it would know when it ended, but since it’s reading from console, you have to explicitly tell it that the input is over. On Linux you do this by pressing
^D(Ctrl+D), on Windows^Z(Ctrl+Z).Note that it has to be done at the start of a new line, i.e. after pressing
Enter, you press^D(^Zon Win).That’s a very good book you’re reading. It’s that good, I guess, it contains the answer to your question.