在c ++中关闭setf?

时间:2017-01-21 17:32:57

标签: c++ setf

我正在使用setf来显示输出中的小数位。

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);

但是,当我将上述代码放在输出之前时,其他输出也会受到影响。有什么办法我只能用一个输出来设置setf吗?就像把它关掉一样?

非常感谢你!

3 个答案:

答案 0 :(得分:6)

setf会返回原始的标记值,因此您可以将其存储起来,然后在完成后将其恢复。

precision也是如此。

所以:

// Change flags & precision (storing original values)
const auto original_flags     = std::cout.setf(std::ios::fixed | std::ios::showpoint);
const auto original_precision = std::cout.precision(2);

// Do your I/O
std::cout << someValue;

// Reset the precision, and affected flags, to their original values
std::cout.setf(original_flags, std::ios::fixed | std::ios::showpoint);
std::cout.precision(original_precision);

阅读some documentation

答案 1 :(得分:2)

您可以使用flags()方法保存和恢复所有标志或unsetf()setf返回的标志

 std::ios::fmtflags oldFlags( cout.flags() );

 cout.setf(std::ios::fixed);
 cout.setf(std::ios::showpoint);
 std::streamsize oldPrecision(cout.precision(2));

 // output whatever you should.

 cout.flags( oldFlags );
 cout.precision(oldPrecision)

答案 2 :(得分:1)

您的问题是您与其他人共享格式化状态。显然,您可以决定跟踪更改并进行更正。但有一种说法:解决问题的最佳方法是防止它发生。

在您的情况下,您需要拥有自己的格式化状态,并且不与其他任何人共享。您可以使用std::ostream的实例与std::cout相同的基础streambuf来拥有自己的格式化状态。

std::ostream my_fmt(std::cout.rdbuf());
my_fmt.setf(std::ios::fixed);
my_fmt.setf(std::ios::showpoint);
my_fmt.precision(2);

// output that could modify fmt flags
std::cout.setf(std::ios::scientific);
std::cout.precision(1);
// ----

// output some floats with my format independently of what other code did
my_fmt << "my format: " << 1.234 << "\n";
// output some floats with the format that may impacted by other code
std::cout << "std::cout format: " << 1.234 << "\n";

这将输出:

my format: 1.23
std::cout format: 1.2e+00

查看那里的实例:live

相关问题