i have tried to use k = getchar() but it doesn\'t work too;
here is my code
#include
int main()
{
float height;
float k=0;
do
I wouldn't use scanf
-family functions for reading from stdin
in general.
fgets
is better since it takes input as a string whose length you specify, avoiding buffer overflows, which you can later parse into the desired type (if any). For the case of float
values, strtof
works.
However, if the specification for your deliverable or homework assignment requires the use of scanf
with %f
as the format specifier, what you can do is check its return value, which will contain a count of the number of format specifiers in the format string that were successfully scanned:
§ 7.21.6.2:
The [scanf] function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
From there, you can diagnose whether the input is valid or not. Also, when scanf
fails, stdin
is not cleared and subsequent calls to scanf
(i.e. in a loop) will continue to see whatever is in there. This question has some information about dealing with that.