gpt4 book ai didi

c++ - 在 C++ 输出流中设置宽度

转载 作者:IT老高 更新时间:2023-10-28 22:13:39 28 4
gpt4 key购买 nike

我试图通过设置不同字段的宽度在 C++ 上创建一个格式整齐的表格。我可以使用 setw(n),做类似的事情

cout << setw(10) << x << setw(10) << y << endl;

或更改 ios_base::width

cout.width (10);
cout << x;
cout.width (10);
cout << y << endl;

问题是,这两种选择都不允许我设置默认的最小宽度,而且每次我向流中写入内容时都必须更改它。

有没有人知道我可以做到这一点而不必无数次重复同一个电话?提前致谢。

最佳答案

你可以创建一个重载的对象 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;
}
};

您现在可以这样调用它:

formatted_output field_output(cout, 10);
field_output << x << y << endl;

关于c++ - 在 C++ 输出流中设置宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7248627/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com