Exercise 1-6 (getchar EOF)
Chapter_1 Exercise_1-5 copy | Exercise_1-7 |
Exercise 1-6 K&R, p. 17
Exercise 1-6. Verify that the expression getchar() != EOF is 0 or 1.
test.c download
#include <stdio.h> // for getchar(), putchar(), EOF
// test boolean value of getchar() != EOF
// true is 1 or not zero, false is 0
int main()
{
int c;
while ((c = getchar()) != EOF)
{ // print as integer:
if (c != '\n') {printf("%d", c != EOF);}
else {putchar('\n');}
}
printf("%d\n", c != EOF);
}
/*
gcc test.c -o test
./test // input from the keyboard
Hello // Enter (not EOF, but two chars)
11111
-1 // Enter
11
// Ctrl+D in Linux, Ctrl+Z then Enter in Windows (EOF)
0
./test < test.c // redirect input to source file
11...110
./test < test // input binary file
11...110
*/
Note:
1 is printed as an integer as
it is different from the character
'1', see the
ASCII_code.
Test with
putchar(49); putchar('1'); putchar('\n');
Chapter_1 Exercise_1-5 copy | BACK_TO_TOP | Exercise_1-7 |
Comments
Post a Comment