我使用setf在输出中显示小数位。
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);但是,当我将上面的代码放在输出之前时,其他输出也会受到影响。有没有什么方法可以只对一个输出使用setf?比如关掉它?
非常感谢!
发布于 2017-01-22 01:36:21
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。
发布于 2017-01-22 02:02:37
您可以使用flag()方法保存和恢复所有标志,也可以使用由setf返回的unsetf()方法
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)发布于 2017-01-23 01:57:53
您的问题是您与其他人共享格式化状态。显然,您可以决定跟踪更改并更正它们。但有一句话说:解决问题的最好方法是防止它发生。
在您的情况下,您需要有自己的格式化状态,并且不能与其他任何人共享。通过使用与std::cout具有相同底层streambuf的std::ostream实例,您可以拥有自己的格式化状态。
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
https://stackoverflow.com/questions/41782392
复制相似问题