How can I convert string to double in C/C++?


Here is an example to convert a string to double.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   char s[20] = "18.2894 is a number";
   char *p;
   double result;
   result = strtod(s, &p);
   cout<<"The number after conversion of string : "<<result;
   return(0);
}

Output

The number after conversion of string : 18.289400

In the above program, a char type array s[20] is declared which is initialized with a alphanumeric characters. The function strtod() is used to convert that string into a double number.

char s[20] = "18.2894 is a number";
char *p;
double result;
result = strtod(s, &p);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

745 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements