To test whether scanf
successfully scanned a float
in this situation, you should use:
if (1 != scanf("%f", &lista2.pret))
goto ero2;
The float
type does not use NULL
to indicate there is no value. NULL
is used with pointers that way—a pointer can have either the address of an actual object or can have the “value” NULL
. However, unlike some other languages, C does not generally have a null value that indicates an object is not holding a valid value. NULL
is intended for use just with pointers, not with integers, floating-point values, or other types of objects.
The floating-point type actually does have a “value” to indicate the object is not holding a number. It is called a NaN, for Not a Number, and is NAN
in source code after including <math.h>
. You could test whether lista2.pret
is a NaN. However, since NaNs are not numbers, they cannot be equal to anything, so you would not test with lista2.pret == NAN
. Instead, you would use isnan(lista2.pret)
.
However, scanf
does not indicate failure by putting a NaN in a float
. scanf
indicates failure by its return value. It returns the number of conversions it successfully performed. So, when using scanf(%f, &lista2.pret)
to convert some input to a float
, the result will be 0 or 1 to indicate 0 or 1 successful conversions. It may also be EOF
to indicate some input failure occurred. So, to test whether scanf
successfully scanned a float
, compare its return value to 1.
(Incidentally, you should know that fflush(stdin)
is an extension to the base C language that is implementation dependent. You are likely using Microsoft Windows. On other C implementations, fflush(stdin)
may not work the same way and could break your program.)