Javier Lam
Javier Lam

Reputation: 21

scanf cannot detect EOF but getchar is able to detect EOF input?

I was just wondering why my code does not register my CTRL+ Z input? When i input CTRL+ Z it does not exit the while loop somehow.

However when I substitute the scanf() function with a getchar() function, it suddenly works! could anyone out there help enlighten me on this?

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

int main(){
    char grade;
    while( grade != EOF){
        scanf("%c" , &grade);
        switch(grade){
        case 'a':
            printf("you got an a!\n");
            break;
        case 'b':
            printf("you got a b!\n");
            break;
        case'\n':
            break;
        default:
            printf("error :(\n");
            break;
        }
    }
    printf("Hello world!\n");
    return 0;
}

Upvotes: 2

Views: 658

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

You need to check the return value of scanf() function to get the expected EOF. Checking the argument for EOF after the scanning failed is wrong, and may invoke undefined behavior, in case the argument is of type automatic local and not initialized.

Quoting from the man page (emphasis mine)

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.

That said, a char is not enough to hold a value of EOF, if you have to store the return value of scanf() call, use an int.

Upvotes: 1

Related Questions