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); }
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 sendEOF… I’m not sure how to do it in other OS’s. To test this program you might want to changeEOFto'\n'which will cause it to stop when you press enter.