Reputation: 337
I am trying reading floating point numbers (command line input). Is this the right way?
sscanf(argv[i], "%f", &float)
Upvotes: 0
Views: 2935
Reputation: 18492
Using sscanf()
with an element of argv
is one way to extract a float
from a command line argument. You should also check the return value to see if a float
was actually extracted from the string and stored into your variable.
Perhaps a better way is using strtod()
, since you can perform better validation with it's second argument. You can use that pointer to check that the last character used in the conversion was the last character in the string. ie. You could check that "3.5abc"
contained a valid float, but the whole string wasn't one single valid float.
If what you mean by command line input is reading input from stdin
, then that has nothing to do with argv
and you should instead be using scanf()
or fgets()
+ strtod()
.
Note that there's also the function atof
which is essentially a version of strtod
that doesn't give you the extra error checking capability. From the man pages it's just: strtod(nptr, (char **) NULL);
. C99 also provides the function strtof()
, which returns a float
instead of a double
. You can assign a double
to a float
and have it implicitly converted, so don't think that using strtod()
will cause a problem.
Upvotes: 2