Click to See Complete Forum and Search --> : C EOF example problem


jeremymh
08-14-2003, 11:18 PM
I've just started reading the book "The C Programming Language (http://www.amazon.com/exec/obidos/tg/detail/-/0131103628/103-4790363-3842269) ". This edition, although the newest, is around 15 years old. Although I've been told it's up to date (as it is ANSI C)

I've gotten to an example that goes like this

#include <stdio.h>

main()
{
int c;

while ((c = getchar()) != EOF)
putchar(c);
}


This seems to work alright, as any text I type appears on screen (except I have to ctrl-c out of the program as I don't know how to put the EOF on the keyboard)

Then he mentions that you need the brackets around the c = getchar() because the != will be done before the =

And he suggests that we try it without the brackets to see what happens (it should output a 1 or a 0)

Unfortunately the program didn't seem to act any differently. I tried the following code, just to see if the compiler has a different order to what he defines, but it still acts exactly the same.
#include <stdio.h>

main()
{
int c;
while (c = (getchar() != EOF))
putchar(c);
}


I'm using gentoo linux, bash, gcc (compiling with "cc gettext.c" and running it as the a.out exec) which all should be the latest stable version gentoo has in portage.

Can anyone shed some light on the situation? is it me, the book, gcc, bash or what?

Strogian
08-14-2003, 11:36 PM
It shouldn't output a 1 or 0, it should output '\1's and '\0's. Actually, true is defined as anything that isn't 0, so GCC might just choose to use whatever value was returned by getchar(). It all depends on how strict the standard actually is.

...

OK, I just compiled the program, and I think I know what your problem REALLY is. (I'll leave the above, just in case it's helpful to anyone :))

Compile the first program. Type in a word and hit ENTER. It will get repeated back at you. I'm guessing that you never tried hitting ENTER? Maybe? That's all I got. :) Linux apparently buffers the input until a full line can be read, and then it makes it available to the program. The second program will not repeat it back at you. It will indeed output a series of 0x01 characters. Oh, and to input a EOF from the keyboard, use Ctrl+D.

jeremymh
08-15-2003, 02:27 AM
Wow, it all makes sense now. Thanks.
If I type more than one letter and press enter it loops many times, one for each letter and once for the "enter", taking them each from the buffer.
or in that example it just has white space where the \0 would be.

Thanks once again.

Stuka
08-15-2003, 11:46 AM
Just a note - Ctrl-D is the EOF combination for Linux. (Windows uses Ctrl-Z).