Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ofstream reset precision

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?

like image 749
andrea Avatar asked Feb 08 '12 16:02

andrea


1 Answers

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.

like image 154
Lightness Races in Orbit Avatar answered Sep 23 '22 05:09

Lightness Races in Orbit