C++ - 如何重置输出流操纵器标志
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1513625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ - How to reset the output stream manipulator flags
提问by noobzilla
I've got a line of code that sets the fill value to a '-' character in my output, but need to reset the setfill flag to its default whitespace character. How do I do that?
我有一行代码在我的输出中将填充值设置为“-”字符,但需要将 setfill 标志重置为其默认的空白字符。我怎么做?
cout << setw(14) << " CHARGE/ROOM" << endl;
cout << setfill('-') << setw(11) << '-' << " " << setw(15) << '-' << " " << setw(11) << '-' << endl;
I thought this might work:
我认为这可能有效:
cout.unsetf(ios::manipulatorname) // Howerver I dont see a manipulator called setfill
Am I on the wrong track?
我在错误的轨道上吗?
回答by éric Malenfant
Have a look at the Boost.IO_State_Savers, providing RAII-style scope guards for the flags of an iostream.
看看Boost.IO_State_Savers,它为 iostream 的标志提供了 RAII 风格的范围保护。
Example:
例子:
#include <boost/io/ios_state.hpp>
{
boost::io::ios_all_saver guard(cout); // Saves current flags and format
cout << setw(14) << " CHARGE/ROOM" << endl;
cout << setfill('-') << setw(11) << '-' << " " << setw(15) << '-' << " " << setw(11) << '-' << endl;
// dtor of guard here restores flags and formats
}
More specialized guards (for only fill, or width, or precision, etc... are also in the library. See the docs for details.
更专业的守卫(仅用于填充、宽度或精度等...也在库中。有关详细信息,请参阅文档。
回答by deancutlet
You can use copyfmtto save cout's initial formatting. Once finished with formatted output you can use it again to restore the default settings (including fill character).
您可以使用copyfmt来保存 cout 的初始格式。完成格式化输出后,您可以再次使用它来恢复默认设置(包括填充字符)。
{
// save default formatting
ios init(NULL);
init.copyfmt(cout);
// change formatting...
cout << setfill('-') << setw(11) << '-' << " ";
cout << setw(15) << '-' << " ";
cout << setw(11) << '-' << endl;
// restore default formatting
cout.copyfmt(init);
}
回答by John Carter
You can use the ios::fill()
function to set and restore the fill character instead.
您可以使用该ios::fill()
功能来设置和恢复填充字符。
http://www.cplusplus.com/reference/iostream/ios/fill/
http://www.cplusplus.com/reference/iostream/ios/fill/
#include <iostream>
using namespace std;
int main () {
char prev;
cout.width (10);
cout << 40 << endl;
prev = cout.fill ('x');
cout.width (10);
cout << 40 << endl;
cout.fill(prev);
return 0;
}
回答by Dmitry V
You can manually change the setfill flag to whatever you need it to be:
您可以手动将 setfill 标志更改为您需要的任何内容:
float number = 4.5;
cout << setfill('-');
cout << setw(11) << number << endl; // --------4.5
cout << setfill(' ');
cout << setw(11) << number << endl; // 4.5
回答by Matt
The null character will reset it back to the original state:
setfill('\0')
空字符会将其重置回原始状态:
setfill('\0')