[英]Table layout using std::cout
如何在 C++ 流中格式化我的 output 以打印固定宽度的左对齐表格? 就像是
printf("%-14.3f%-14.3f\n", 12345.12345, 12345.12345);
生产
12345.123 12345.123
包括标准的 header <iomanip>
和 go 疯狂。 具体来说, setw
操纵器设置 output 宽度。 setfill
设置填充字符。
std::cout << std::setiosflags(std::ios::fixed)
<< std::setprecision(3)
<< std::setw(18)
<< std::left
<< 12345.123;
您还可以考虑以下之一提供的更友好的功能:
写自 memory,但应该是这样的:
// 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);
此外,如果您打算坚持使用这些格式库中的任何一个,请彻底检查它们在可表达性、可移植性(和其他库依赖性)、效率、国际化支持、类型安全等方面的局限性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.