Why can't I find the value of EOF in C?

前端 未结 6 897
梦毁少年i
梦毁少年i 2020-12-30 13:48

I\'m reading the book \"The C Programming Language\" and there is an exercise that asked to verify that the expression getchar() != EOF is returning 1 or 0. Now

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 14:44

    in your program you are reading character from std input as c = getchar();

    this way you can get ascii value of key pressed, Which will never be equal to EOF.

    because EOF is End of File.

    better you try to open any existing file and read from the file, so when it reached End Of File(EOF), it will quit the while loop.

    well the answer in the book is:

    int main()
    {
      printf("Press a key\n\n");
      printf("The expression getchar() != EOF evaluates to %d\n", getchar() != EOF);
    }
    

    try to understand the program, it gets a key, which will not be equal to EOF so it should always print "The expression getchar() != EOF evaluates to 0".

    hope it helps.......

提交回复
热议问题