I'm trying to write a helper function that can be used for parsing integers from config files and from a text-based protocol (written by machine, not by a human). I've read How to parse a string to an int in C++? but the solutions there don't address all the issues. I would like something that will (from most to least important):
Any ideas on a solution? Is there an easy way to wrap the existing parsing machinery to meet these requirements, or is it going to end up being less work to write the parser myself?
There are some quick hacks, parse as normal (non robust) and do some small checks in the input (for example if parsing an non-negative number check that it doesn't have '-' character).
The ultimate test of robustness is to convert the integer back to text, and check that the input text and the output text is the same. When working in the text version, then you can relax things, like accepting leading 0's or spaces.
You basically want the num_get<char>
facet of the C locale. It's somewhat complicated, so see this example. Basically, you have to call use_facet<num_get<char,string::iterator> > (locale::classic).get(begin, end, ... , outputValue)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With