Data that is text that represents a number can be converted to data that is interpreted as a number. The C++ Standard Library has a set of functions that will do the conversion. What about when you are unsure if the text data is in a form that can be converted? You will get an error that you can avoid by inspecting the data before converting it. The code in the next section shows a pair of functions, is_numeric and is_digit, that provide a way to inspect a full string.
One of the many traditional ways to inspect a value involves you writing code that inspects each character in a string, one-by-one. You kept track of how many characters were numbers. A string was a number when the total digits matched total characters.
You can get distracted writing code like that. A simpler way is possible in C++ using Alexander Stepanov’s generic programming approach. This example came about when reading offline documentation for the STL in which I found no function for inspecting numbers in text like you have in .NET and Java. The functionality may exist and I will scour the Web for details. Meanwhile, I wondered if a generic C++ algorithm could be enlisted to solve the problem in a pinch.
The solution below uses the all_of function. The function returns true if all of the values satisfy a condition. That condition is determined by a function you supply. I wanted to supply the isdigit function in a fashion where the all_of function will supply each character from the string to this function. At the iteration’s end, the string is numeric if every character was identified as a digit. Back to the traditional way of doing things, the all_of function essentially does the same thing, but in a very compact and easy to remember way.
Code is on GitHub @ MichaelGautier/CodeExpo/IsNumeric