Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming: EOF as a character

Tags:

c

char

eof

When programming C for the command console, what happens when you have a function that tries to use SCANF to ask user input for a CHAR variable, and the user types CTRL+Z (EOF) and hits enter?

For example:

char promptChar()
{
    char c;
    printf("Enter a character: ");
    scanf("%c", &c);
    return c;
}

If the user types CTRL+Z and hits enter, what will promptChar() return? Because if I understand EOF, it's an int.

like image 690
Thai-Duong Nguyen Avatar asked Dec 09 '22 19:12

Thai-Duong Nguyen


1 Answers

First things first:

SCANF is not defined by the language.
CHAR is not defined by the language.

Ok, with that out of the way ...

The scanf() function returns an integer. That integer is the number of input items assigned or the value of the macro EOF if an input failure occurs before the first conversion.
You didn't check the return value of the scanf() call, so you have no idea what happened. Everything might have worked ok, or the input stream might have ended before the first conversion, or (not for %c) there might have been a conversion failure.

Test the return value of scanf(). Indeed, always test the return value of all <stdio.h> functions.

char ch;
int result = scanf("%c", &ch);
if (result == 1) /* all ok */;
else if (result == 0) /* conversion failure: value of `ch` is indeterminate */;
else if (result == EOF) /* input failure; value of `ch` is indeterminate */;

When the result of the scanf() call is EOF, if you want more information about the reason for input failure, you can use feof() and/or ferror().

else if (result == EOF) {
    if (feof(stdin)) {
        /* no data in input stream */
    }
    if (ferror(stdin)) {
        /* error if input stream (media ejected? bad sector? ...?)
    }
}

To answer your question: what will promptChar() return?

It will return an indeterminate value of type char.
You could follow the example of library function that deal with characters and return an int from promptChar(). That would be the value of the character read cast to unsigned char or a negative int (EOF) in case of error. Read the description for fgetc(), for instance.

like image 166
pmg Avatar answered Dec 12 '22 08:12

pmg