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);

Dani AI

Generated

Brief summary and a modern clean option that fits the thread: ’s original line double x = atof(num); relied on old C APIs (others here pointed that out). ’s stream idea is fine for simple use, and correctly raised the need for stricter error checking. For code written today prefer the standard C++ helpers that give clear error semantics.

Use std::stod (since C++11) for simple, exception-based conversion. It accepts an optional size_t* index so you can detect trailing garbage and it throws std::invalid_argument or std::out_of_range on failure — convenient if you want to handle errors with try/catch. Example pattern:

std::string num = "45.00";
std::size_t pos = 0;
double x = std::stod(num, &pos);
if (pos != num.size()) {
    // partial parse or extra characters -> handle as error
}

(de.cppreference.com)

Use std::from_chars (header <charconv>, C++17) when you need the fastest, no-alloc, no-throw parsing and explicit error codes. It is locale-independent and returns both a pointer to the first unparsed character and an error code you can test:

#include <charconv>
std::string_view sv = "45.00";
double value;
auto res = std::from_chars(sv.data(), sv.data()+sv.size(), value);
if (res.ec == std::errc() && res.ptr == sv.data()+sv.size()) {
    // success
} else {
    // invalid input or out_of_range
}

(cppreference.com)

Quick notes that matter years later: std::stod discards leading whitespace and recognizes locale-dependent decimal characters via the C locale; std::from_chars does NOT skip leading whitespace and is explicitly locale-independent, so trim or validate input first if you use it. For portability, verify your toolchain’s floating-point from_chars support (vendor support varied historically). Use the exception style (stod) when you prefer exceptions; use from_chars for low-level, high-throughput parsing. (de.cppreference.com)

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 . 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.