C Programming: EOF as a symbol

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

For instance:

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

If the user types CTRL + Z and gets into it, what will return promptChar ()? Because if I understand EOF, this is an int.

+4
source share
3 answers

First of all:

SCANF not language defined.
CHAR not defined by language.

Okay, with that out of the way ...

The scanf() function returns an integer. This integer is the number of input elements assigned or the value of the EOF macro if an input failure occurs before the first conversion.
You did not check the return value of the scanf() call, so you do not know what happened. Everything could work fine, or the input stream might finish before the first conversion, or (not for% c), the conversion might have failed.

Check the return value of scanf() . Indeed, it always checks 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 calling scanf() is EOF , if you want more information about the cause of the 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 undefined value of type char.
You can follow the example of a library function that processes characters and returns an int from promptChar() . This will be the value of the character read in unsigned char , or negative int ( EOF ) in case of an error. Read the description of fgetc() , for example.

+11
source

From Linux help scanf(3) :

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

Note that this excerpt deals with the return value of scanf , not the result parameters.

+4
source

It depends on the shell you are using, but you really shouldn't have to design any program to wait for control characters to be read from the interactive prompt.

Most command shells will intercept some control characters and use them to force the shell to do something. For example, ctrl-s and ctrl-q often start and stop alternating output characters. ctrl-z on some shells will actually be taken as a command to close the shell.

-one
source

All Articles