Is there a equivalent of TryParse in C++(gcc) ?
I would like to parse a string which may contain (+31321) and store it as long. I know phone numbers are stored as strings and string matched but for my needs , I would like to store them as long and sometimes they might contain pluses (+). What would parse it in C++?
In fact, before convert the string into a number, the numbers should be "normalized" to a common format. This requires removing all symbols, and replace them with proper representation.
But you must be very care about representing telephone numbers (that are NOT numbers: they are not subjected to regular arithmetic) as string: Number beginning with one or more zeroes are not the same as the ones with the zeroes removed:
00 is the typical replacement for +, but a number without the 00 (or +) in front should be prefixed by 00c where c is the country code.
You need to do some pre-processing to come to a uniform string representation, before converting, otherwise you risk to "alias" different things.
The trouble with strtoul() and family there is no real way to test for failure.
If it fails to parse then it returns 0 without setting errno (which is only set on overflow).
boost lexical cast
Doing it using streams
Using scanf:
the input extraction operator >> (i hope it's an acceptable name) applies and returns a stream&, that has a bool operator, meaning the extraction has been succesfully attempted. For instance, from the Cubbi answer:
This will succed, of course, given the appropriate content of s.
Somewhat different (easier but not type safe) also the scanf family has practical tools available in c++ as well c. You could of course write the example this way:
A subset of regular expressions make this rather powerful: for instance to match a comma separed multi fields with left space trimming:
+31321
can be parsed as along
with the usual stream extraction operators.demo: http://ideone.com/4rmlp
Although parsing an actual phone number (with parentheses, dashes, extensions, etc) may not be as simple.