c++ - Can you use a stringstream to safely convert bidirectionally? -
c++ - Can you use a stringstream to safely convert bidirectionally? -
i have case double converted string using stringstream. now, have value somewhere else (no, have no access original double), have parse formatted string.
ofcourse, can read stringstream well, safe? work, values?
std::ostringstream doubletostring; double mydouble = 3.14; doubletostring << mydouble; std::string converteddouble = doubletostring.str(); std::istringstream stringtodouble(converteddouble); double newdouble; stringtodouble >> newdouble;
in illustration above, mydouble equal newdouble?
note: marginal differences (0.00000000001) not concern.
no, not work. can prove using minor modification of code:
#include <sstream> #include <iostream> #include <string> #include <cassert> int main() { std::ostringstream doubletostring; double 0 = 0; double mydouble = 3.14/zero; doubletostring << mydouble; std::string converteddouble = doubletostring.str(); std::cout << "converteddouble = " << converteddouble << std::endl; std::istringstream stringtodouble(converteddouble); double newdouble; stringtodouble >> newdouble; std::cout << "newdouble = " << newdouble << std::endl; assert(newdouble == mydouble); }
when run code on machine, output:
converteddouble = inf newdouble = 0 xlat: xlat.cpp:19: int main(): assertion `newdouble == mydouble' failed. aborted (core dumped)
update: note if start double in range of representable floating point numbers on particular machine (that std::numeric_limits<double>::min() <= x <= std::numeric_limits<double>::max()
) still isn't guaranteed. illustration of seek code above double mydouble = 1/3.0;
. issue 1 of precision when emitting double
string. can seek address modifying code utilize this:
doubletostring << std::setprecision(std::numeric_limits<double>::digits10) << mydouble;
this has effect of setting precision many decimal digits needed integer value always survive transformation , double
. however, still won't work double values!
double mydouble = pow(1/3.0, 300);
this value cause assert trigger. reason digits10
only mantissa portion of floating point number , doesn't represent exponent. getting pedantic here, can set right value as:
constexpr int dblprecision = std::numeric_limits<double>::digits10 + ceil(log10(std::numeric_limits<double>::max_exponent10)); doubletostring << std::setprecision(dblprecision) << mydouble;
note needed in double-to-string conversion direction , not other way.
so understanding input value must in indicated range, , provided set precision conversion string, think result in original double, assuming no bugs in implementation of compiler or library.
c++ formatting stringstream
Comments
Post a Comment