i have a string that i want to convert to double. i know atof is a standard library function for that, however, the input argument to atof is (const char*), not string type that i have.

does anyone know how i might convert my string num to double ? thanks

string num = "45.00";
double x = atof(num);

Recommended Answers

All 5 Replies

You can use istringstream

std::istringstream stm;
stm.str("3.14159265");
double d;
stm >>d;

If you are sure that the string is in double conversible format like 1.2e-2, grunt's method is the eaisest. But if you want to check the input string if it can be converted as double, e.g 123abc will be converted as 123 in grunt's method. For easier error checking better use strtod. Just checking the value of end to be null will be enough.

#include <sstream>
#include <cstdlib>
int main ()
{
    std::istringstream stm;
    char* end = 0 ;
    
    double d;
    
     stm.str("123abc");// Invalid input string
    stm >>d;  
     std::cout << d << std::endl; // Returns 123
     
    stm.str("123e-2");
    stm >>d;  
    std::cout << d << std::endl;  

     d = strtod( "123abc", &end ); // Invalid input string
     if ( *end == 0 )
        std::cout << d << std::endl;
    else
         std::cout << "Error Converting\n"; // Reports error
         
    d = strtod( "123e-2", &end );
    if ( *end == 0 )
        std::cout << d << std::endl;
    else
        std::cout << "Error Converting\n";
        
    return 0;
}

PS:
To get the characters from num , use num.c_str()

thank you all. for the time being my strings are all convertible to double. but i might need wolfpack's suggestion just to be safe

If you want error checking then I would suggest you to use Exception Handling. That will be a better option.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.