views:

102

answers:

3

Hello, I have a scientific application for which I want to input initial values at runtime. 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 runtime, and everything else is set at compile time (except for output files and a few other totally simple things).

Thanks,

Joel

+3  A: 
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
Tuomas Pelkonen
There is no good reason to use `atof`.
Steve Jessop
That might be true, but you could also say, why there is no good reason to use it...
Tuomas Pelkonen
@Tuomas It's difficult to do proper error checking when using atof(). There are a few questions on here talking about the advantages of the strto*() set over the others.
Ioan
+5  A: 

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

Ioan
+1. Note that `strtof` and `strtold` (for long double) are part of the C99 spec. For C89/C90, stick with `strtod`.In my opinion, `sscanf` is often overkill and `atof` is like a watered-down version of `strtod` without any way to check for errors.
tomlogic
`strto*( )` is generally the correct way to handle this sort of thing, as it has well defined and useful error handling semantics.
Stephen Canon
A: 

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.

semiuseless
I do pretty much have the structure you suggest in your first paragraph. But the user has the option of supplying a list on the command-line if he (me) so wishes. I wouldn't normally do that, but it could be useful during quick debugging sessions.
Joel J. Adamson