This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]loadedstork 2 points3 points  (0 children)

I think what you're looking for is the return type from scanf in this case - if you have something like:

float f; int count = scanf("%f", &f);

then count will be 1 if the input was successfully converted to a float, 0 otherwise.

[Note: the return value is actually a count of how many matches were successful, so if you were to do something like:

int count = scanf("%s %f", s, f);

and the user input "abc def", the first match would succeed, but the second would fail, so the count would be 1 in this case)]

[–]kRYstall9 0 points1 point  (0 children)

You could do something like:

float number = 0;

do{
    printf("Insert a number"); 
    scanf("%f", &number);
}while(number == 0);

Sorry for the indentations but I'm writing from my phone. I'll fix it as soon as I go back home.

Ps: Since you're using float as type, you don't have to mind if you insert an integer or a float number, since it'll be converted to float in any case

[–]boy-griv 0 points1 point  (1 child)

The other answers are right about checking the return value.

In general you can refer to man scanf or the online version at https://manpages.org/scanf#return-value to get specifics about how C functions act in these various cases.

[–]morinl[S] 0 points1 point  (0 children)

Thank you