This post will discuss how to determine if a string is numeric in C++. The solution should check if the string contains a sequence of digits.

1. Using Loop

A simple solution is to iterate over the string until a non-numeric character is encountered. If all characters are digits, the string is numeric. This solution does not work with negatives or floating-point numbers.

Download  Run Code

2. Using std::find_if

We can also use the standard algorithm std::find_if from the <algorithm> header, which accepts a predicate to find the element in the specified range. It can be used as follows to find the position of the first non-digit character. If all characters in the string are digits, the string must be numeric. This solution only works for positive integers.

Download  Run Code

3. Using string::find_first_not_of

The string::find_first_not_of function searches the string for the first character that does not match any of the specified characters. It can be used as follows to determine if a string is numeric.

Download  Run Code

4. Using std::all_of

Starting with C++11, we can use the std::all_of function that returns true if the specified predicate holds for all the elements in the specified range. It can be used as follows to determine if a string is numeric.

Download  Run Code

5. Using strtol() function

Alternatively, we can use the strtol() C standard library function that parse a C-string str as an integral number in the specified base and return a zero value if conversion is not possible. It can be used to parse a std::string and determine if the string is numeric, as shown below.

Download  Run Code

6. Using Boost

If you’re already using boost library, you can parse the C++ string with boost::lexical_cast<>() function. It throws an boost::bad_lexical_cast exception if conversion is not possible. This also works for negative integers and floating-point numbers. Here’s the complete code:

Download Code

7. Using Regex

Finally, we can use a regex to determine if a string is numeric. The following solution currently works for positive and negative integers. It can be easily extended to work with floating-point numbers.

Download  Run Code

That’s all about determining if a string is numeric in C++.