在 C++ 输出流中设置宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7248627/
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
Setting width in C++ output stream
提问by Andre Manoel
I'm trying to create a neatly formatted table on C++ by setting the width of the different fields. I can use setw(n), doing something like
我试图通过设置不同字段的宽度在 C++ 上创建一个格式整齐的表格。我可以使用 setw(n),做类似的事情
cout << setw(10) << x << setw(10) << y << endl;
or change ios_base::width
或更改 ios_base::width
cout.width (10);
cout << x;
cout.width (10);
cout << y << endl;
The problem is, neither of the alternatives allows me to set a default minimum width, and I have to change it everytime I'll write something to the stream.
问题是,这两种选择都不允许我设置默认的最小宽度,而且每次我向流中写入内容时都必须更改它。
Does anybody knows a way I can do it without having to repeat the same call countless times? Thanks in advance.
有没有人知道我可以做到这一点而不必无数次重复同一个电话?提前致谢。
回答by Jason
You can create an object that overloads operator<<
and contains an iostream
object that will automatically call setw
internally. For instance:
您可以创建一个重载operator<<
并包含一个iostream
将在setw
内部自动调用的对象的对象。例如:
class formatted_output
{
private:
int width;
ostream& stream_obj;
public:
formatted_output(ostream& obj, int w): width(w), stream_obj(obj) {}
template<typename T>
formatted_output& operator<<(const T& output)
{
stream_obj << setw(width) << output;
return *this;
}
formatted_output& operator<<(ostream& (*func)(ostream&))
{
func(stream_obj);
return *this;
}
};
You can now call it like the following:
您现在可以像下面这样调用它:
formatted_output field_output(cout, 10);
field_output << x << y << endl;
回答by ssell
I know this is still making the same call, but I know of no other solution from what I am getting from your question.
我知道这仍在进行相同的呼叫,但我从您的问题中得到的信息中没有其他解决方案。
#define COUT std::cout.width(10);std::cout<<
int main()
{
std::cout.fill( '.' );
COUT "foo" << std::endl;
COUT "bar" << std::endl;
return 0;
}
Output:
输出:
..........foo
..........bar
回答by Ray
why not just create a function?
为什么不创建一个函数?
pseudocode e.g.
伪代码例如
void format_cout(text, w) {
cout << text << width(w);
}
That's a bit scrappy but hopefully you get the idea.
这有点草率,但希望你能明白。