Search code examples
ckernighan-and-ritchie

C Programming Exercise from the K&R Book


Any idea why the following code doesn't print the amount of characters in the input? I've taken this straight from the K&R book. Learning C at the moment and this is really confusing, looks to me like I'm never reaching EOF. If that's the case then why would this be used as an example?

#include <stdio.h>

main()
{
    double nc;

    for (nc = 0; getchar() != EOF; ++nc)
        ;
    printf("%d\n", nc);
}

Solution

  • The program looks correct, your problem is that you have to send EOF (end-of-file) to the command line after your input since the standard input is treated as a file. I think in a linux terminal you can press Ctrl+D to send EOF... I'm not sure how to do it in other OS's. To test this program you might want to change EOF to '\n' which will cause it to stop when you press enter.