使用std :: cout的表格布局

Vol*_*lkA 12 c++ formatting iostream stream

如何在C++流中格式化输出以打印固定宽度的左对齐表?就像是

printf("%-14.3f%-14.3f\n", 12345.12345, 12345.12345);
Run Code Online (Sandbox Code Playgroud)

poducing

12345.123     12345.123
Run Code Online (Sandbox Code Playgroud)

Kon*_*lph 17

包括标准标题<iomanip>并发疯.具体而言,setw操纵器设置输出宽度.setfill设置填充字符.


kmk*_*lan 15

std::cout << std::setiosflags(std::ios::fixed)
          << std::setprecision(3)
          << std::setw(18)
          << std::left
          << 12345.123;
Run Code Online (Sandbox Code Playgroud)


Ano*_*ous 11

您还可以考虑以下其中一种提供的更友好的功能:

  • Boost.Format(功能强大,但非常重,比其他提到的时间和内存分配更多)
  • Loki.SafeFormat
  • FastFormat(相对较新,但速度极快的库,与其他类型不同,也是类型安全的)

从内存写入,但应该是这样的:

// 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);
Run Code Online (Sandbox Code Playgroud)

此外,如果您打算坚持使用这些格式化库中的任何一个,请在可表达性,可移植性(以及其他库依赖性),效率,国际化支持,类型安全性等方面彻底检查它们的局限性.