Reputation: 411
Scanf in C language, I am a little confused about the return value.
In the instruction, it says:
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
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
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