我试图通过设置不同字段的宽度来在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;
问题是,这两种选择都不允许我设置默认的最小宽度,而且每次我要向流中写入内容时,我都必须更改它。
有没有人知道我不需要无数次重复同一个电话就能做到这一点?提前谢谢。
发布于 2011-08-31 03:28:26
您可以创建一个重载operator<<
的对象,并包含一个将在内部自动调用setw
的iostream
对象。例如:
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;
发布于 2011-08-31 03:32:47
我知道这仍然是在打同样的电话,但我从你的问题中得到的结果是没有其他解决方案的。
#define COUT std::cout.width(10);std::cout<<
int main()
{
std::cout.fill( '.' );
COUT "foo" << std::endl;
COUT "bar" << std::endl;
return 0;
}
输出:
..........foo
..........bar
发布于 2011-08-31 03:54:48
为什么不直接创建一个函数呢?
伪代码,例如
void format_cout(text, w) {
cout << text << width(w);
}
这有点争强好胜,但希望你能明白。
https://stackoverflow.com/questions/7248627
复制相似问题