Check if Char Array is a Number in C++

This tutorial will discuss about a unique way to check if char array is a number in C++.

We can try to convert the char array to a double value. If we are successful in conversion, then it means we can convert a char array to double.

We can use the stod() function to convert a char array to a double value. If given string / char array can not be converted into a valid double value, then the stod() function will raise an exception i.e. either invalid_argument or out_of_range . This way, we can confirm if a char array contains a valid number value or not.

Let’s see the complete example,

#include <iostream>
#include <string.h>

// Returns true of the string contains a number
bool isNumber(const char* arr )
{
    bool result = false;
    try
    {
        // convert string to double
        double value = std::stod(arr);
        result = true;
    }
    catch( const std::exception& )
    {}

    return result;
}

int main()
{
    char arr[10] = "234.8";

    // Check if char array / string is a number
    if(isNumber (arr) )
    {
        std::cout<<"Char Array contains the Number \n";
    }
    else
    {
        std::cout<<"Char Array does not contain a Number \n";
    }

    return 0;
}

Output :

Char Array contains the Number

Summary

Today we learned about several ways to check if char array is a number in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top