Is there a way to check if a string can be a float in C?

Viewed 8434

Checking if it can be an int is easy enough -- just check that every digit is between '0' and '9'. But a float is harder. I found this, but none of the answers really work. Consider this code snippet, based on the top (accepted) answer:

float f;
int ret = sscanf("5.23.fkdj", "%f", &f);
printf("%d", ret);

1 will be printed.


Another answer suggested using strpbrk, to check if certain illegal characters are present, but that wouldn't work either because 5fin7 wouldn't be legal, but inf would.


Yet another answer suggested checking the output of strtod. But consider this:

char *number = "5.53 garbanzo beans"
char *foo;

strtod(number, &foo);

printf("%d", isspace(*foo) || *foo == '\0'));

It'll print 1. But I don't want to remove the isspace call entirely, because " 5.53 " should be a valid number.


Is there a good, elegant, idiomatic way to do what I'm trying to do?

6 Answers
Related