简体   繁体   English

如何取消设置 std::cout 精度?

[英]How to unset std::cout precision?

cout.precision(m);

cout << "specified number of digits pi_float = " << a_0 << endl;

In my further computation when I try to print pi with double precision, only m digits are printed.在我尝试以double精度打印pi时的进一步计算中,仅打印m 位 How do I unset std::cout.precision ?如何取消设置std::cout.precision

Typically you just set it to whatever you need when you need it, but if you really do want to restore the previous settings you can save and reload it like this:通常,您只需在需要时将其设置为所需的任何内容,但如果您确实想恢复以前的设置,您可以像这样保存并重新加载它:

std::streamsize prev_precision = std::cout.precision(); // save old precision
std::cout.precision(m);
// ... use the stream for whatever ...
std::cout.precision(prev_precision); // restore old precision

You can do this for the other format settings as well (width, fill, scientific notation, boolalpha, etc.).您也可以对其他格式设置(宽度、填充、科学记数法、boolalpha 等)执行此操作。

I have an opensource github project that does just that using RAII if you want a pre-packaged solution covering everything (or just example code to do it).我有一个开源github 项目,如果您想要一个涵盖所有内容的预打包解决方案(或者只是示例代码),它可以使用 RAII 来做到这一点。

Store it and restore it存储它并恢复它

auto p = std::cout.precision(m); cout << "specified numbr of digits pi_float = " << a_0 << endl;
std::cout.precision(p);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM