For reference, I’m copying this example (nearly) letter for letter from page 18 in The C Programming Language, Second Edition.
#include <stdio.h>
/*count characters in input, 2nd version*/
main(){
double n;
for (n = 0; getchar() != EOF; ++n)
;
printf("%.0f\n", n); /*this never prints*/
}
I wasn’t sure if it was my version of gcc (I’m a noob):
% gcc --version
gcc (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
Copyright (C) 2010 Free Software Foundation, Inc.
Because
for (n = 0; getchar() != EOF; ++n)
printf("%.0f",n); /*returns 0123456...n*/
I tried printing “foo” instead of value n, just to see. It still isn’t printing.
What am I missing here? I don’t like moving ahead while ignoring little problems like these.
=====================================
EDIT
So the end result should be:
% gcc ./counter.c -o ./counter
% ./counter
foo
3
Right now, this is the output from the first snippet:
% ./counter
foo
0123
And the second one:
% ./counter
foo
^C
%
If you are on an OSX or linux box, you need to type
Ctrl+Don its own line to generate an EOFcharacter. On Windows,Ctrl+Zon its own line. Don’t typeCtrl+Zon a unix box because that will just send your proces to the background.You are typing
Ctrl+Cwhich is break, and will send aSIGTERMto your program.On my mac, I get:
Or if you don’t want to signal the EOF condition, use echo and a pipe:
Note that the
EOFhas to be on its own line. a^Dis printed, and then 6 overwrites the ^, so it looks like the output is6D.Of course, in the two above examples, the characters being counted are
h e l l o \n. If you don’t want a newline, do this: