I would like to know once and for all how to convert a double to a const char*

I've tried it a few times, but have never succeeded, I know it can be done, but I haven't figured out how to yet. I've tried some different things. Sometimes it won't compile, and sometimes the program crashes, and other times it ends up as an empty string.

Dani AI

Generated

You cannot cast a double to const char*. A cast only reinterprets bytes; it does not turn 12.35 into the text "12.35". As and hint, you must format the value into characters, then pass a pointer to that character storage.

C-style, fixed buffer (bounds-checked):

#include <cstdio>

char buf[64];
double x = 12.35;
int n = std::snprintf(buf, sizeof buf, "%.3f", x);
if (n < 0 || static_cast<size_t>(n) >= sizeof buf) {
    // handle error or truncation
}
// use buf as const char*

Prefer snprintf over sprintf because it limits writes to the buffer size. See the <cstdio> signatures for sprintf/snprintf. (en.cppreference.com)

Modern C++ options that still give you const char* when needed:

// C++11: simple, but fixed formatting
std::string s = std::to_string(x);   // prints 6 digits after the decimal by default
const char* p = s.c_str();           // valid while 's' is alive and unmodified

std::to_string follows printf-style defaults (six fractional digits; uses the C locale), which may or may not be what you want. (en.cppreference.com) The pointer from c_str() stays valid until the string is modified or destroyed, so do not return it from a function unless the std::string outlives that use. (my.eng.utah.edu)

If you want precise control without allocations, use C++17 to_chars into your own buffer:

#include <charconv>

char buf2[64];
auto [ptr, ec] = std::to_chars(std::begin(buf2), std::end(buf2),
                               x, std::chars_format::fixed, 3);
if (!ec) { *ptr = '\0'; /* use buf2 */ }

to_chars is locale-independent, non-allocating, and does not append a null terminator for you. (en.cppreference.com)

Bonus: In C++20, std::format gives printf-like control but returns a std::string; call c_str() if a const char* is required. (en.cppreference.com)

Recommended Answers

All 5 Replies

U can try sprintf().

Amit

depends on how you want to use it. If you want to pass a pointer to a double as a parameter to some function that takes char* then typecasting might work, depending on what that function is going to do with it. Normally, however, you will have to convert it storing the results in either a character array or a std::string object.

Two ways come to mind: sprintf() will convert and store in a character array, while std::stringstream will convert and store in std::string object.

>I would like to know once and for all how to convert a double to a const char*
Casting doesn't work. You're not converting the double to a string with a cast, you're telling the compiler to use the binary representation of the double as characters in a string. For a value like 12.35, that's not going to give you a string like "12.35". You need to take the printed value (like if you write the double using cout) and store it in a string. That's really really painful to do manually with floating-point, so you should use sprintf or stringstream like Ancient Dragon said.


____________________
Le Parkour LifeStyle

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.