ofstream reset precision

andrea picture andrea · Feb 8, 2012 · Viewed 10.7k times · Source

I'm using c++ to manipulate txt files. I need to write some numbers with a certain precision so I'm doing:

    ofstrem file;
    file.open(filename, ios::app);
    file.precision(6);
    file.setf(ios::fixed, ios::floafield);
    //writing number on the file.....

now I need to write other stuff, so I need to reset precision. how can I do it?

Answer

Lightness Races in Orbit picture Lightness Races in Orbit · Feb 8, 2012

Retrieve the stream's original precision value first with precision(), store it, change it, do your insertions, then change it back to the stored value.

int main() {
   std::stringstream ss;
   ss << 1.12345 << " ";

   std::streamsize p = ss.precision();

   ss.precision(2);
   ss << 1.12345 << " ";

   ss.precision(p);
   ss << 1.12345;

   cout << ss.str();  // 1.12345 1.1 1.12345
}

Live demo.