Reputation:
I wrote the following program to understand the behavior of EOF:
#include<stdio.h>
int main ()
char c = 0;
printf("Enter some chars, EOF stops printing:");
while ((c == getc(stdin)) != EOF)
printf("c = %c, (int) c = %d\n", c, (int) c);
return 0;
}
However, if I input something such as abcd
I get this output:
c = a, (int) c = 97
c = a, (int) c = 97
c = a, (int) c = 97
Upvotes: 1
Views: 118
Reputation: 399833
You must read the documentation better; getc()
returns int
, because EOF
doesn't fit in a char
.
Also, you're using both scanf()
and getc()
, which will make things confusing due to the input stream buffering.
Try something like this:
#include <stdio.h>
int main()
int c = 0;
printf("Enter some chars, EOF stops printing:");
while ((c = getc(stdin)) != EOF) {
printf("c = %c, (int) c = %d\n", c, c);
}
return 0;
}
I also added the missing }
in your code, and removed the cast of c
in the call to printf()
, that's not needed now that c
is int
. This is the proper type for the %c
formatting specifier too, by the way.
Upvotes: 1
Reputation: 182639
You've got a ==
instead of a =
so you never store whatever getc
returns:
while ((c == getc(stdin)) != EOF) {
^^
And of course c
should be int
, not char
.
Upvotes: 7