In my program, I use sscanf to check whether a string is of a given format. To do so, I provide the number of arguments in the format string and check whether sscanf returns that same number when parsing the input.
As part of a primitive parser, I want to check whether a string matches one of many formats. The sscanf function is variadic, so how do I deal with the varying number of arguments I need to pass?
Currently, I just pass a very large number of arguments (e.g. 50) to the function, and just hope that the format strings don’t contain more arguments.
Is there any better way to do this?
You really need something heavier than
scanf. You have to tellscanfwhat format your input is in; it can’t figure anything out on its own.If you have access to POSIX, look at
regex.hit’s probably everything you need.Otherwise, you’re stuck rolling your own.
lexandyaccare nice if the format is rather complex, but otherwise, eitherstrtokor (getchar+switch) is probably the way to go.Edit:
Since you can use POSIX, here’s an simple example of how to extract data from a regex in c. (error checking excluded for brevity.)
Prints