如何在C++流中格式化输出以打印固定宽度的左对齐表格?像使用std :: cout的表格布局
printf("%-14.3f%-14.3f\n", 12345.12345, 12345.12345);
东西poducing
12345.123 12345.123
如何在C++流中格式化输出以打印固定宽度的左对齐表格?像使用std :: cout的表格布局
printf("%-14.3f%-14.3f\n", 12345.12345, 12345.12345);
东西poducing
12345.123 12345.123
包含标准头<iomanip>
和发疯。具体来说,setw
操纵器设置输出宽度。 setfill
设置填充字符。
std::cout << std::setiosflags(std::ios::fixed)
<< std::setprecision(3)
<< std::setw(18)
<< std::left
<< 12345.123;
您也可以考虑通过这些一个提供更友好的功能:
从存储器的写入,而应是东西沿着这些路线:
// Dumb streams:
printf("%-14.3f%-14.3f\n", 12345.12345, 12345.12345);
// For IOStreams you've got example in the other answers
// Boost Format supports various flavours of formatting, for example:
std::cout << boost::format("%-14.3f%-14.3f\n") % a % b;
std::cout << boost::format("%1$-14.3f%2$-14.3f\n") % a % b;
// To gain somewhat on the performance you can store the formatters:
const boost::format foo("%1$-14.3f%2$-14.3f\n");
std::cout << boost::format(foo) % a % b;
// For the Loki::Printf it's also similar:
Loki::Printf("%-14.3f%-14.3f\n")(a)(b);
// And finally FastFormat.Format (don't know the syntax for decimal places)
fastformat::fmtln(std::cout, "{0,14,,<}{1,14,,>}", a, b);
另外,如果你打算坚持通过这些格式化库中的任何一个,在可表达性,可移植性(和其他库依赖性),效率,国际化支持,类型安全性等方面彻底检查它们的局限性。
+1由于字面上发疯。 – Anonymous 2009-02-26 13:35:24
不要忘记左对齐的`std :: left`。 – 2014-02-04 09:40:54