harumomo503
harumomo503

Reputation: 411

Return value EOF of scanf in C

Scanf in C language, I am a little confused about the return value.

In the instruction, it says:

  1. EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs.
  2. EOF is also returned if a read error occurs, in which case the error indicator for the stream is set.

First, I am not sure what they mean by if the end of input is reached before the first successful conversion or before a matching failure occurs. How is that possible?

Second, I am not sure the difference between read error and matching failure?

Upvotes: 3

Views: 5138

Answers (2)

Weather Vane
Weather Vane

Reputation: 34585

The function scanf() returns the number of fields successfully read and converted. But if I type (Windows) Ctrl-Z for the input, that indicates EOF. In Linux, I think that may be Ctrl-D? So if you haven't entered meaningful values, scanf() indicates failure in one way or another.

Typically, you test for the number of inputs required, and this will cover the EOF situation too.

if (1 != scanf("%d", &i))
    printf ("No valid input\n");

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182761

First, I am not sure what they mean by if the end of input is reached before the first successful conversion or before a matching failure occurs. How is that possible?

Imagine you're trying to read a character from a file and you're at the end of the file. The end of input will be reached before any successful conversion or matching attempt takes place.

Second, I am not sure the difference between read error and matching failure?

A read error means you were unable to read data from the FILE. A matching failure means you were able to read data but it didn't match what was expected (for example, reading a for %d.)

Upvotes: 4

Related Questions