The goal is to write a simple character counting program in C. If written like this:
#include <stdio.h>
main()
{
long nc;
for(nc = 0; getchar() != EOF; ++nc)
printf("%ld\n", nc);
}
the last number listed in its output will be the correct number of characters. However, if written like this:
#include <stdio.h>
main()
{
long nc;
nc = 0;
while(getchar() != EOF)
{
++nc;
printf("%ld\n", nc);
}
}
the last number in its output will always be larger by one than the true number of characters in the input string. I learned that this is because pressing Enter after inputting the desired string introduces a newline character which gets counted and produces the error. To eliminate that error is trivial, but my question is why doesn't the same problem occur in the program written above?
For example, the first program will correctly output 0 if ran without input. The second one however will output 1 in the same scenario. Why the difference?