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,
Pointers in C/C++ [Full Course]
#include <iostream> #include <string.h> // Returns true, if string is // converted to diuble successfully bool converToDouble(const char* arr, double& value ) { bool result = false; try { // 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; ; } else { std::cout<<"Char Array can not be converted to an Double \n"; } return 0; }
Output :
Double Value is : 23.178
Summary
Today we learned about several ways to convert char array to double or number. Thanks.