Precision setting for string stream worldwide

I use stringstream in my entire project, which contains more than 30 files. I recently overcame the problem caused by stringstring, where I parsed double into stringstream, and accuracy was lost. So now I want to set the accuracy for all files. Is there a way to install it somewhere on a global scale, so I don’t need to make changes everywhere, getting into every file. Someone suggested I see if it can be used locally.

Please help me with the problem, and if you have a code or some link to the code, it will be more useful.

+5
source share
3 answers

Probably the easiest way to do this is to replace the use of stringstream with your entire program with your own class, which inherits from stringstream:

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

The method is precisiondefined as a path to the inheritance chain in std::ios_baseand controls the number of significant digits or the number of digits after the decimal fraction, if the manipulator works fixed.

For more detailed code and output, see this insert in the code .

+6
source

To add to Patrick's answer, the standard requirements for std::ios_baseare given in the standard:

27.4.4.1.3:

Table 92: effects of 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
+1
source

include mystringstream.h, , , .

  • , sstream.
  • Your STL implementation should not have specialized basic_stringstream <char, char_traits<char>, allocator<char> >
  • Your STL implementation or any other header you include should not have a stringstream already created

In doing so, he worked in this simple code 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
    }
  };
}

I personally do not like this solution, because it significantly changes the behavior of the standard library, and does not expand it.

0
source

All Articles