How to disable std :: fixed and return to C ++ default setting

My code is:

std::vector<double> thePoint(4); thePoint[0] = 86; thePoint[1] = -334.8836574; thePoint[2] = 24.283; thePoint[3] = 345.67675; ofstream file1(tempFileName, ios::trunc); file1 << std::setprecision(16) << thePoint[0] << " "; file1 << std::fixed << std::setprecision(2) << thePoint[1] << " "; file1 << std::setprecision(16) << thePoint[2] << " "; file1 << std::setprecision(16) << thePoint[3]; 

I get:

86 -334.88 24.28300000000000 345.6767500000000

I want:

86 -334.88 24.283 345.67675

Odd formatting is needed to interface with other picky code.

+6
source share
2 answers

You must do this:

 file1 << std::fixed << std::setprecision(2) << thePoint[1] << " "; file1.unsetf(ios_base::fixed); file1 << std::setprecision(16) << thePoint[2]; 

A floatfield format floatfield can take either of two possible values ​​(using fixed and scientific manipulators) or none of them (using ios_base::unsetf ).

+8
source

You can do this by setting floatfield to null:

 file1.setf( std::ios_base::fmtflags(), std::floatfield ); 
However, in practice this is rare. The usual protocol is to save format flags and restore them when you are done:
 std::ios_base::fmtflags originalFlags = file1.flags(); // ... file1.flags( originalFlags ); 

Of course, you usually use RAII to do this in a real program. You must have an IOSave class in your toolbox that stores flags, precision, and the fill character in its constructor, as well as restoring them in the destructor.

Also not a good practice to use std::setprection etc. directly. A better solution would be to define your own manipulators, with names like pression or volume , and use them. This is logical markup and means that you control the format, for example. pressure from one and not spread it throughout the program. And if you write your own manipulators, it is relatively easy to restore the original formatting options at the end of the full expression. (The manipulator objects will be temporary, destroyed at the end of the full expression.)

+5
source

Source: https://habr.com/ru/post/923571/


All Articles