ceofgetchar

Reading EOF as a char in C


I know it might sound stupid but how can I exit this loop ?

#include <stdio.h>
#include <stdlib.h>

int main(){
    char c;
    do {
        c = getchar();
        printf("%c", c);
    }while(c != EOF);

    return 0;
}

I'm reading a book and trying to do the following exercise: "Verify that the expression getchar() != EOF is 0 or 1" If I read the value of EOF stored in an integer value it will be equal to -1 but if I try to catch a -1 as a char is mindfuck. From what I've understood EOF is a value which is not assigned to any other char ..

anyone can help ?

edit1: I know that c should be an Integer ... I'm reading it as a char intentionally.

edit2:

int main(){
    int c;
    while((c = getchar()) != EOF)
    {
        printf("%d\n", c);
    }
    return 0;
}

----->

int main(){
    int c;
    int i = 0;
    char str[2];
    while((c = getchar()) != EOF)
    {
        str[i] = c;
        ++i;
        if(i > 1) i = 0;
        if(str[0]=='-'&&str[1]=='1')
        {
            c = EOF; // doens't exit loop
        }
        else printf("%d\n", c);


    }
    return 0;
}

Why I can't understand this.


Solution

  • It might help you to understand what's going on if you change the program like this:

    #include <stdio.h>
    
    int main(){
        int c;
        do {
            c = getchar();
            printf("%d\n", c);
        } while(c != EOF);
    }
    

    You'll notice that I have:

    1. declared c as int
    2. printed it using %d

    If I run this program and type "abc" and then hit Enter and then CTRL-D, this is what I see:

    97
    98
    99
    10
    -1
    

    97, 98, and 99 are the ASCII codes for a, b, and c. 10 is the code for newline, aka \n. And then that -1 is the EOF that resulted when I typed CTRL-D. (If you're on Windows, you'd use CTRL-Z and another Enter instead.)

    In this program, although c is an int variable, that does not mean that it does not hold characters! In C, characters are represented by small integers which are their codes in the machine's character set. Here's a modification to demonstrate this:

    int c;
    int nch = 0;
    char string[100];
    do {
        c = getchar();
        printf("%d", c)
        if(c >= 32 && c < 127) {
            printf(" = '%c'", c);
            string[nch++] = c;
        }
        printf("\n");
    } while(c != EOF);
    string[nch] = '\0';
    printf("You typed \"%s\"\n", string);
    

    Now it prints

    97 = 'a'
    98 = 'b'
    99 = 'c'
    10
    -1
    You typed "abc"
    

    There's no problem calling

    printf(" = '%c'", c);
    

    even though c is an int and %c is for printing characters.
    There's no problem assigning

    string[nch++] = c;
    

    even though c is an int and string is an array of characters.