3 Ways to Check if a String Has Only Numbers in C++
In fact, there are several ways, however, these are the most indicated and/or used.
There are many common tasks in C++ that we often forget about. Therefore, it is interesting to always return to the basics to train and establish knowledge.
This type of check can be used in numerous situations and there are more than 3 ways to check whether or not a
string has only numbers.
In this article we will see the simplest and most commonly used ways!
1. The ‘Like a BOSS!’
The way I usually use and recommend is using the
std::all_of function of the header:
<algorithm> in conjunction with lambda.
I usually call it form: Like a BOSS! 😃 , for being more modern and faster, especially at compile time.
The code boils down to:
std::string shas a letter, so the output will be: There are not only numbers :( , but if we change and recompile the result will be different.
Some people think that RegEx is not a good idea, however, it is a standardized form that works for any programming language and is also functional.
The downside of using RegEx in C++ is the compile time, which increases significantly. In summary the code would be:
In this case the
string shas a character that is not a number: + at the end.
As basic as possible!
Some people prefer orthodox C++, that is, the oldest and closest to C as possible.
So this basic code would be:
Very easy, right?