Double to Const Char*

前端 未结 4 826
既然无缘
既然无缘 2021-01-11 17:55

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 fput

相关标签:
4条回答
  • 2021-01-11 18:30

    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;
    
    0 讨论(0)
  • 2021-01-11 18:37

    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!
    
    0 讨论(0)
  • 2021-01-11 18:40

    Use this funcition :

    const char* ConvertDoubleToString(double value){
        std::stringstream ss ;
        ss << value;
        const char* str = ss.str().c_str();
        return str;
    }
    
    0 讨论(0)
  • 2021-01-11 18:44

    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;
    
    0 讨论(0)
提交回复
热议问题