DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Cast double to const char* (http://www.daniweb.com/forums/thread93947.html)

prushik Oct 23rd, 2007 3:08 am
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.

amt_muk Oct 23rd, 2007 4:12 am
Re: Cast double to const char*
 
U can try sprintf().

Amit

Ancient Dragon Oct 23rd, 2007 8:08 am
Re: Cast double to const char*
 
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.

Ptolemy Oct 23rd, 2007 11:45 am
Re: Cast double to const char*
 
>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.

vmanes Oct 23rd, 2007 11:49 am
Re: Cast double to const char*
 
Here's an interesting discussion on the topic:
http://www.codeproject.com/string/st...onversions.asp

Seta00 Nov 12th, 2008 7:46 am
Re: Cast double to const char*
 
http://www.cplusplus.com/reference/c...o/sprintf.html
____________________
Le Parkour LifeStyle


All times are GMT -4. The time now is 10:23 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC