Computer Science Canada

need help with changing a double to a string

Author:  myob [ Thu Jan 20, 2005 7:48 pm ]
Post subject:  need help with changing a double to a string

i need help with changing a double variable to a string variable. if anyone knows a command that can change a double variable to a string variable, it will be greatly appreciated

Author:  wtd [ Thu Jan 20, 2005 8:05 pm ]
Post subject: 

C:

code:
#include <stdlib.h>
#include <stdio.h>

int main()
{
   char foo[256];
   double d = 42.27;

   sprintf(foo, "%f", d);

   return 0;
}


C++:

code:
#include <string>
#include <sstream>

int main()
{
   std::stringstream ss;
   double d = 42.27;
   std::string foo;

   ss << d;
   foo = ss.str();

   return 0;
}

Author:  myob [ Thu Jan 20, 2005 8:35 pm ]
Post subject: 

still got a question.. does this work under ccc_win.cpp?

edit:
btw, im using dirty borland c++, dirty school wont let us use visual c++

Author:  rizzix [ Thu Jan 20, 2005 8:43 pm ]
Post subject: 

jeez its the other way around.

borland == clean... vc++ == dirty. gcc == compatibility. gcc is prefered for development.. but borland is prefered for teaching.

Author:  wtd [ Thu Jan 20, 2005 8:44 pm ]
Post subject: 

That code will work with any standards compliant compiler. If it doesn't work with your compiler, then your compiler is deficient.

Author:  md [ Thu Jan 20, 2005 9:25 pm ]
Post subject: 

This also works, and it has the advantage of not using sprintf

code:

#include <stdlib.h>

#define PRECISION 100

...

    char *string
    double d = 10.1010101;
    gcvt(d, PRECISION, string);
...


Author:  wtd [ Thu Jan 20, 2005 9:29 pm ]
Post subject: 

Problem is, that's not standard.


: