流外重置精度
我正在使用 C++ 来操作 txt 文件。 我需要以一定的精度写一些数字,所以我正在这样做:
ofstrem file;
file.open(filename, ios::app);
file.precision(6);
file.setf(ios::fixed, ios::floafield);
//writing number on the file.....
现在我需要写其他东西,所以我需要重置精度。 我该怎么办?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先使用
precision() 检索流的原始精度值,存储它,更改它,执行插入,然后将其更改回存储的值。
现场演示。
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.Live demo.
有两种可能的解决方案。如果您正在处理一大块
使用相同格式参数的输出,您可以使用一些东西
像这样:
只需在执行输出的块的顶部定义它的一个实例。
然而,大多数时候,我会定义自己的操纵器,
源自类似的内容:
实现有点棘手,因为你必须考虑
如果在同一个表达式中使用多个操纵器,则
编译器可以按任何顺序构造它们(从而破坏它们)
请。因此:
派生操纵器然后在其
setState
实现中执行其必须执行的操作。鉴于此,您可以编写如下内容:而不必担心保存和恢复格式化状态。
There are two possible solutions. If you're handling a large block of
output which uses the same formatting parameters, you can use something
like this:
Just define an instance of it at the top of the block doing the output.
Most of the time, however, I'll be defining my own manipulator, which
derives from something like:
The implementation is a bit tricky, since you have to take into account
that if several manipulators are used in the same expression, the
compiler can construct them (and thus destruct them) in any order it
pleases. So:
The derived manipulator then does whatever it has to in its implementation of
setState
. Given this, you can write things like:without having to worry about saving and restoring the formatting state.
一种解决方案:
One solution: