簡體   English   中英

使用 std::cout 的表格布局

[英]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;

您還可以考慮以下之一提供的更友好的功能:

  • Boost.Format (功能強大,但很重,比其他提到的更多時間和 memory 分配)
  • Loki.SafeFormat
  • FastFormat (相對較新,但速度極快的庫,與其他庫不同,也是類型安全的)

寫自 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM