basic c i/o and EOF

D

Dave Casserly

Below is the code ive written just to count the characters typed in. I
assumed EOF is -1, so if i type -1 and then press enter shouldnt the
program end? It orks if i put something like 'q' in the while loop to
end the loop.

what is up?

<code>

#include <stdio.h>

void main() {

long nc;

nc = 0;
while (getchar() != 'EOF') {
++nc;
}
printf("%ld\n", nc);

}

</code>

thanks
Dave
 
C

Chris Dollin

Dave said:
Below is the code ive written just to count the characters typed in. I
assumed EOF is -1, so if i type -1 and then press enter shouldnt the
program end? It orks if i put something like 'q' in the while loop to
end the loop.

what is up?

<code>

#include <stdio.h>

void main() {

`void main()` is not portable. `int main()` is. Do not use `void main()`.
long nc;

nc = 0;
while (getchar() != 'EOF') {

'EOF' is not portable and does not mean what you thought. You want
EOF (no quotes), which is a macro defined in stdio.

['EOF' is a multi-character character constant, which I recall as
having an implementation-defined meaning. Presumably most implementations
will compose its value out of the values of 'E', 'O', and 'F', but
how it composes them is anyone's guess, so you can't depend on it.]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top