Double to Const Char*

前端 未结 4 846
既然无缘
既然无缘 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 
    bool convertFromStr(string &str, T *var) {
      istringstream ss(str);
      return (ss >> *var);
    }
    
    template 
    string convertToStr(T *var) {
      ostringstream ss;
      ss << *var;
      return ss.str();
    }
    

    Example:

    double d = 1.234567;
    string str = convertToStr(&d);
    cout << str << endl;
    double d2;
    convertFromStr(str, &d2);
    cout << d2 << endl;
    

提交回复
热议问题