Convert Char Array to Double or Number in C++

This tutorial will discuss about a unique way to convert char array to double or number.

In C++, the string.h header file provides a function stod(). It accepts a character pointer as an argument, and interprets its contents as a floating point number. It returns a double value. We can use this function to convert a char array to a double.

If the given string can not be converted into a double value, or it is out of range, then it will raise an exception i.e. either invalid_argument or out_of_range exception. Therefore, while using the stod() function for converting a char array to a double, we need to make sure that we catch all the exceptions.

Let’s see the complete example,

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

// Returns true, if string is
// converted to diuble successfully
bool converToDouble(const char* arr, double& value )
    bool result = false;
        // convert string to double
        value = std::stod( arr);
        result = true;
    catch( const std::exception& )
    return result;

int main()
    char arr[10] = "23.178";
    double value = 0;

    // convert string to double
    if(converToDouble(arr, value) )
        std::cout<<"Double Value is : " << value << std::endl; ;
        std::cout<<"Char Array can not be converted to an Double \n";
    return 0;

Output :

Double Value is : 23.178


Today we learned about several ways to convert char array to double or number. 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