我在整个项目中使用 stringstream,该项目有 30 多个文件。我最近克服了由 stringstring 引起的问题,在该问题中我将 double 解析为 stringstream 并且精度丢失。所以现在我想设置所有文件的精度。有什么方法可以将其设置在全局某个地方,这样我就不需要在每个文件的各处进行更改。有人建议我看看是否可以使用语言环境。
请帮我解决这个问题,如果您有代码或任何代码链接,它将更有用。
I am using stringstream in my entire project which has more than 30 files. I recently overcomed an issue caused by stringstring where I was parsing the double to stringstream and there was a precision lost. So now I want to set the precision for all the files. Is there any way to set it somewhere globally so that I dont need to make changes everywhere going into each file. Someone suggested me to see if its possible using locale.
Please help me out with the issue and if you have code or any link to code, it will be more useful.
发布评论
评论(3)
也许最简单的方法是用您自己的继承自
stringstream
的类替换整个程序中对 stringstream 的使用:precision
方法是在继承链的上游定义的在std::ios_base
中,并控制有效位数,或者如果使用fixed
操纵器,则控制小数点后的位数。有关更多示例代码和输出,请参阅此粘贴在键盘上。
Probably the easiest way to do this is to replace your use of stringstream throughout your program with your own class that inherits from
stringstream
:The
precision
method is defined way up the inheritance chain instd::ios_base
, and controls the number of significant digits, or the number of digits after the decimal if thefixed
manipulator is in play.For more example code and output see this paste on codepad.
只是为了补充帕特里克的答案,标准中列出了
std::ios_base
的默认精度:27.4.4.1.3:
表 92:basic_ios::init() 效果
Just to add to Patrick's answer, the default precisions for
std::ios_base
are laid out in the Standard:27.4.4.1.3:
Table 92: basic_ios::init() effects
如果您愿意将所有包含语句更改为您自己的内部头
mystringstream.h
,您可以使用模板专门化来实现此目的,但有这么多警告我不会这样做。sstream
的任何地方都使用此标头。basic_stringstream, allocator 。 >
也就是说,它在这个简单的 键盘示例。
我个人不喜欢这个解决方案,因为它本质上修改了标准库的行为,而不是扩展它。
If you are willing to change all of your include statements to your own internal header
mystringstream.h
, you can use template specialization to pull this off, but with so many caveats I would not do it.sstream
previously.basic_stringstream <char, char_traits<char>, allocator<char> >
That being said, it worked in this simple codepad example.
I don't personally like this solution because it essentially modifies the behavior of the standard library, instead of extending it.