Double to Const Char *

How can I convert double to const char and then convert it back to double?

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

I am using Visual C ++ 2010 Express Edition.

+7
source share
4 answers

If you just want to write double values ​​to a file, you can simply write it without converting them to const char* . Converting them to const char* is redundant.

Just use std::ofstream like:

  std::ofstream file("output.txt")' double d = 1.989089; file << d ; // d goes to the file! file.close(); //done! 
+6
source

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; 
+8
source

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; 
+3
source

Use this function:

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

All Articles