FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


[C++] Double/Float to char []





CaBz
Hello,

I am working on a small program that could be useful for me one day, but for now not. This program consists of reading data from a file, then put a "total" when it reaches the EOF.

My problem is that I don't know/understand how to change the type of the variable to another type.

Example :

dData is a double variable.
cData[10] is a string variable.

I want to put the value of dData into cData, but how ?

Thanks for any answers !
badai
String ToString(double f, int ndec = 4)
Indi
badai wrote:
String ToString(double f, int ndec = 4)

Er... no.

First of all, cData[10] is not a string variable, it is a char array variable. If it were a string variable, you could just do:
Code:
double dData = 1.0;
string sData;

ostringstream o;
o << dData;
sData = o.str();

// Or just use boost::lexical_cast

But since it's a char array variable, you need another step:
Code:
double dData = 1.0;
char cData[10];

ostringstream o;
o << dData;

strncpy(cData, o.str().c_str(), 9);
cData[9] = '\0';
CaBz
Which class I need to include to make the 'ostringstream' thing working ?

EDIT : I just found it, it's "#include <sstream>"
darth_revan
C code for that is sprintf.

Code:

float asd;
char abc[50];
//something that changes asd
sprintf(abc, "asd is: %x.yf", asd);

For example, 2.525 is written as %1.3f, but its best if you use 6.2f.

edit: I just saw that it's c++ thread.
Indi
If you're usin C99, snprintf() is better than sprintf() anyway. And if you're not usin C99, you should use a platform specific function, like _snprintf(). sprintf() is evil.
Related topics
Reply to topic    Frihost Forum Index -> Scripting -> Others

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.