I have just started to learn programming (C) as a hobby, by myself. I'm using K&R.
main()
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
}
Verify that getchar() != EOF IS 0 OR 1
I think I understand what is happening:
- c is assigned the next character from the keyboard
- c is checked whether it is EOF or not
- c is assigned 1 or 0, depending if it is EOF or not.
- character is shown on output, or if EOF ends the program.
However, my solution is wrong, so clearly I am not understanding something:
main ()
{
int c;
while ((c = getchar()) != EOF)
printf("%d\n", c);
}
This just prints the value of the character. And also prints "10" if I press Carriage Return key.
I thought that it would print c. However, it is printing the character's value rather than the 1 or 0 value.
I know c is assigned 1 or 0 after comparing it with EOF. But I'm not sure what logic I can use to show this. It seems I need to somehow 'get out' of showing the character value, and instead show the comparison value. Does it mean I need to get out of the while loop? If so, I don't know how (and this is just a guess).
How can I simply verify that c = 1 or 0?
And also, how should I know this? There must be something fundamental that I should learn from this, I suppose.
main ()
{
int c;
while ((c = getchar()) != EOF != 0 != 1)
putchar(c);
}
I also did this and I think this seems to work. As it doesn't output any characters, but I'm not sure if this is the solution they are looking for...