OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Numbers In C++

Code snippet for how to Check If A String Contains Only Numbers In C++ with sample and detail explanation

Knowing if a string contains only numeric characters can be quite helpful and necessary in many scenarios. This article will explain and show an easy way to check if a string consists only of numbers in C++.

Code snippet: Check Numeric Characters in a String

#include <iostream>
#include <string>

bool isNumeric(std::string str)
{
    for (int i = 0; i < str.length(); i++)
      if (isdigit(str[i]) == false)
        return false; //when one non numeric character is found, return false
    return true;
}

int main() {
    std::string str;
    std::cout << "Enter a string: ";
    std::cin >> str;
    if (isNumeric(str))
        std::cout << "The string is numeric.\n";
    else
        std::cout << "The string is not numeric.\n";
    return 0;
}

Code Explanation for Check Numeric Characters in a String

Firstly, we include necessary header files - <iostream> for input-output operations, and <string> for string functions.

Then we define a function, isNumeric(), that takes a string as its input and returns a boolean value. This function is used to determine if the string contains only numeric characters.

In this function, we loop over each character in the string using a for loop. For each character, we use the isdigit() function. The isdigit() function checks whether a character is a numeric character (0-9) or not. If it’s a numeric character, the function returns a non-zero integer, and if it isn’t, the function returns 0.

If the isdigit() function returns zero (which implies the character is not a number), our isNumeric function breaks off from the loop and returns false.

If the loop finishes without finding any non-numeric character (i.e., all characters are numeric), the function returns true.

Lastly, inside the main() function, we take a string as input from the user. We pass this input string str to our isNumeric() function. If the function returns true, we print “The string is numeric.” If it returns false, we print “The string is not numeric.”

And that is all. We have our code that checks if a string contains only numbers in C++.

c-plus-plus