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

前端 未结 6 752
梦毁少年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:30

    Because if c is EOF, the while loop terminates (or won't even start, if it is already EOF on the first character typed). The condition for running another iteration of the loop is that c is NOT EOF.

    0 讨论(0)
  • 2020-12-30 14:41

    EOF can be triggered through keyboard by pressing keys ctrl+d in Unix and ctrl+c in Windows.

    Sample Code:

        void main()
        {
               printf(" value of getchar() != eof is %d ",(getchar() != EOF));
               printf("value of eof %d", EOF);
        }
    

    Output:

    [root@aricent prac]# ./a.out 
    a
     value of  getchar() != eof is 1 value of eof -1
    [root@aricent prac]# ./a.out 
    Press    ctrl+d
     value of   getchar() !=  eof is 0 value of eof -1[root@aricent prac]# 
    
    0 讨论(0)
  • 2020-12-30 14:43

    To display the value of EOF

    #include <stdio.h>
    int main()
    {
       printf("EOF on my system is %d\n", EOF);
       return 0;
    }
    

    EOF is defined in stdio.h normally as -1

    0 讨论(0)
  • 2020-12-30 14:44

    make it c!=EOF instead. Because you want to print the result of the expression and not the character.

    0 讨论(0)
  • 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.......

    0 讨论(0)
  • 2020-12-30 14:45
    Here is my one,
    i went through the same problem and same answer but i finally found what every body want to say.
    System specification :: Ubuntu 14.04 lts
    Software :: gcc
    
    
    yes the value of EOF is -1 based on this statement
    printf("%i",EOF);
    
    but if your code contain like this statement
    while((char c=getchar)!=EOF);;
    and you are trying to end this loop using -1 value, it could not work.
    
    But instead of -1 you press Ctrl+D your while loop will terminate and you will get your output. 
    
    0 讨论(0)
提交回复
热议问题