简体   繁体   中英

Reading floating point numbers

I am trying reading floating point numbers (command line input). Is this the right way?

sscanf(argv[i], "%f", &float)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM