Can I use std:fixed or std::setprecision() with >> operator?

喜夏-厌秋 提交于 2019-12-24 00:46:37

问题


std::istringstream loses precision when converting a string to long double. Can I use something similar to std::fixed or std::setprecision()?

I am using c++ 11 and targeting QNX platform.

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

int main(){
    long double convertedNumber;
    std::string numberString ("5.94865747678615882510631e+4931");

    //From string to long double
    std::istringstream iss(numberString);
    iss >> convertedNumber;

    std::cout<< std::setprecision(30) << numberString << "\n";
    std::cout<< std::setprecision(30) << convertedNumber << "\n";

    return 0;
}

The output is

5.94865747678615882510631e+4931
5.9486574767861588254e+4931

回答1:


The issue you're having has nothing to do with your use of setprecision or streams.

An 80-bit double (long double) is not large enough to store the number you're trying to store with the precision you want. 80-bit doubles have a mantissa of 64 bits, meaning the precision of numbers it can represent is the same as a 64-bit integer, which itself is limited to 19 [decimal] digits of value. The value you're trying to store is (5.9486_57476_78615_88251_0631) 24 decimal digits of value, meaning it's simply too precise to be accurately represented by your program.

If you want to store this value in your program, you need to keep it in its string representation or find an arbitrary precision library for representing/manipulating these numbers. My recommendation is to use the boost.multiprecision library, though it does depend on your organization/task permitting use of the C++ Boost Libraries.




回答2:


Yes it will work, these are functions which are used for any stream. a stream is a construct for receiving and sending of bytes A stream uses the

<< Insertion operator

And the >> extraction operator

The std::setprecision function is a stream manipulator which can be applied for any stream EDIT if your question is why its not at a precision of 30, its because you lost precision when doing

iss >> convertedNumber;

And the iss stream is the most precise number according to your input. Stick to the answer of Xirema for a more technical explanation and solution



来源:https://stackoverflow.com/questions/53960678/can-i-use-stdfixed-or-stdsetprecision-with-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!