开发者

What is the standard way to parse floats at runtime in C?

I have a scientific application for which I want to input initial values at run time. I have an option to get them from the command line, or to get them from an input file. Either of these options are input to a generic parser that uses strtod to return a linked list of initial values for each simulation run. I either use the command-line argument or getline() to read the values.

The question is, should I be rolling my own parser, or should I be using a parser-generator or some library? What is the standard method? This is the only data I will read at run time, and everything else is开发者_运维问答 set at compile time (except for output files and a few other totally simple things).

Thanks,

Joel


Also check out strtof() for floats, strtod() for doubles.


sscanf

is probably the standard way to parse them.

However, there are some problems with sscanf, especially if you are parsing user input.

And, of course,

atof


In general, I prefer to have data inputs come from a file (e.g. the initial conditions for the run, the total number of timesteps, etc), and flag inputs come from the command line (e.g. the input file name, the output file name, etc). This allows the files to be archived and used again, and allows comments to be embedded in the file to help explain the inputs.

If the input file has a regular format:
For parsing, read in a full line from the file, and use sscanf to "parse" the line into variables.

If the input file has an irregular format: Fix the file format so that it is regular (if that is an option). If not, then strtof and strtod are the best options.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜