10

How can I convert a double into a const char, and then convert it back into a double?

I'm wanting to convert the double to a string, to write it to a file via fputs, and then when I read the file, it will need to be converted back into a double.

I'm using Visual C++ 2010 Express Edition.

Justin White
  • 8,273
  • 4
  • 19
  • 9
  • If you are using C++ do you really want to use char and fputs? – David Heffernan Jun 19 '11 at 19:24
  • 1
    Better to use binary files, instead of text files and store the double "as-is". Then read it "as-is". Ensure that "structure" of file doesn't change. – Ajay Jun 19 '11 at 19:39
  • I'd like to support what Ajay said: it is much more effective to use binary files and store the doubles as doubles rather than converting them to a decimal representation (if only because this is likely to introce rounding errors!), only to be able to write it to a text file in string form. – leftaroundabout Jun 19 '11 at 22:41
  • 1
    Another thing: don't say "convert `double` to const `char*`", you never want to do this. What you actually mean is "convert `double` to array of char and give me a pointer to this array". Or simply "convert `double` to `string`". – leftaroundabout Jun 19 '11 at 22:44

4 Answers4

8

Since you added C++ to your tags, I suggest you use std::stringstream:

#include <sstream>

stringstream ss;
ss << myDouble;
const char* str = ss.str().c_str();
ss >> myOtherDouble;
Paul Manta
  • 30,618
  • 31
  • 128
  • 208
  • 1
    You should add that after any call to a non-const member function the pointer should not be treated as valid. – lccarrasco Jun 19 '11 at 19:34
8

If you just want to write the double values to file, you can simply write it, without converting them into const char*. Converting them into const char* is overkill.

Just use std::ofstream as:

 std::ofstream file("output.txt")'

 double d = 1.989089;

 file << d ; // d goes to the file!

 file.close(); //done!
Nawaz
  • 353,942
  • 115
  • 666
  • 851
3

You can use these functions to convert to and from:

template <class T>
bool convertFromStr(string &str, T *var) {
  istringstream ss(str);
  return (ss >> *var);
}

template <class T>
string convertToStr(T *var) {
  ostringstream ss;
  ss << *var;
  return ss.str();
}

Example:

double d = 1.234567;
string str = convertToStr<double>(&d);
cout << str << endl;
double d2;
convertFromStr<double>(str, &d2);
cout << d2 << endl;
Morten Kristensen
  • 7,412
  • 4
  • 32
  • 52
1

Use this funcition :

const char* ConvertDoubleToString(double value){
    std::stringstream ss ;
    ss << value;
    const char* str = ss.str().c_str();
    return str;
}