全局设置stringstream的精度

时间:2010-03-04 20:19:53

标签: c++ stringstream

我在整个项目中使用stringstream,其中包含30多个文件。我最近克服了一个由stringstring引起的问题,我将double解析为stringstream并且精度丢失了。所以现在我想为所有文件设置精度。有没有办法在全局范围内设置它,这样我就不需要在每个文件的每个地方进行更改。有人建议我查看是否可以使用区域设置。

请帮我解决这个问题,如果您有代码或任何代码链接,它会更有用。

3 个答案:

答案 0 :(得分:7)

执行此操作最简单的方法可能是将您在整个程序中使用stringstream替换为自己继承自stringstream的类:

class mystringstream : public std::stringstream
{
public:
   mystringstream()
   {
      precision(16); // or whatever your desired precision is
   }
};

precision方法在std::ios_base中的继承链中定义,并控制有效位数,或fixed操纵器所在的小数点后的位数播放。

有关更多示例代码和输出,请参阅this paste on codepad.

答案 1 :(得分:1)

为了补充Patrick的回答,std::ios_base的默认精度列在标准中:

27.4.4.1.3:

表92:basic_ios :: init()效果

Element         Value
rdbuf()         sb
tie()       0
rdstate()       goodbit if sb is not a null pointer, otherwise badbit.
exceptions()    goodbit
flags()         skipws | dec
width()         0
precision()     6
fill()      widen(’ ’);
getloc()        a copy of the value returned by locale()
iarray      a null pointer
parray      a null pointer

答案 2 :(得分:0)

如果您愿意将所有include语句更改为您自己的内部标题mystringstream.h,您可以使用模板专业化来解决此问题,但有很多警告我不会这样做。

  • 您必须确保使用此标题到处以前包含sstream
  • 您的STL实施必须没有专门的basic_stringstream <char, char_traits<char>, allocator<char> >
  • 您的STL实现或您包含的任何其他标头必须没有实例化stringstream

话虽如此,它在这个简单的codepad example中起作用。

// mystringstream.h
namespace std
{
  // This class exists solely to "trick" the compiler into
  // considering this allocator a new, different type
  class newallocator : public allocator<char>
  {
  };

  // template specialize std::stringstream to inherit from basic_stringstream
  // using our newallocator in place of std::allocator<char>
  template <>
  class basic_stringstream<char, char_traits<char>, allocator<char> >
    : public basic_stringstream <char, char_traits<char>, newallocator >
  {
  public:
    basic_stringstream()
    {
      precision(16);  // or whatever precision you like
    }
  };
}

我个人不喜欢这个解决方案,因为它实质上修改了标准库的行为,而不是扩展它。

相关问题