Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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 the original code before I was asked to do that was:

int main()
{
    int c;
    c = getchar();

    while (c != EOF)
    {
        putchar(c);
        c = getchar();
    }  
}

So I thought changing it to:

int main()
{
    int c;
    c = getchar();

    while (c != EOF)
    {
        printf("the value of EOF is: %d", c);
        printf(", and the char you typed was: ");

        putchar(c);
        c = getchar();
    }
}

And 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);
}

Could you please explain to me why my way didn't work?

like image 422
MNY Avatar asked Jan 09 '13 12:01

MNY


People also ask

How do I find my EOF character?

The EOF in C/Linux is control^d on your keyboard; that is, you hold down the control key and hit d. The ascii value for EOF (CTRL-D) is 0x05 as shown in this ascii table . Typically a text file will have text and a bunch of whitespaces (e.g., blanks, tabs, spaces, newline characters) and terminate with an EOF.

How do I print the value of EOF?

1. Since EOF is an integer, we can print it with %d format in the printf. 2. EOF value is printed as -1.

What value does EOF have in C?

EOF is a macro which expands to an integer constant expression with type int and an implementation dependent negative value but is very commonly -1. '\0' is a char with value 0 in C++ and an int with the value 0 in C.


2 Answers

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.

like image 158
Mecki Avatar answered Oct 01 '22 20:10

Mecki


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

like image 35
jim mcnamara Avatar answered Oct 01 '22 21:10

jim mcnamara