954,206 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Cast double to const char*

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.

prushik
Junior Poster
101 posts since Oct 2007
Reputation Points: 61
Solved Threads: 5
 

U can try sprintf().

Amit

amt_muk
Light Poster
48 posts since May 2005
Reputation Points: 14
Solved Threads: 3
 

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.

Ancient Dragon
Retired & Loving It
Team Colleague
30,046 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,342
 

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

Ptolemy
Junior Poster in Training
64 posts since Oct 2007
Reputation Points: 44
Solved Threads: 8
 

Here's an interesting discussion on the topic:
http://www.codeproject.com/string/string_conversions.asp

vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
 
Seta00
Newbie Poster
1 post since Nov 2008
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You