在C 中,我该怎么办才能格式化输出

In C++, what can I do to format my output?

本文关键字:格式化 输出 我该怎么办      更新时间:2023-10-16

例如,如果我的输出是: -

King of Spades
Queen of Hearts
Four of Diamonds
Nine of Clubs
Three of Diamonds
Deuce of Spades
Ace of Hearts

那么我该怎么做才能表现出来: -

 King of Spades
Queen of Hearts
 Four of Diamonds
 Nine of Clubs
Three of Diamonds
Deuce of Spades
  Ace of Hearts

我只需要对齐of's。有人告诉我setw可以提供帮助。

是这样吗?如果可以的话,那么如何?

计算要显示的第一个单词的最大长度,然后用它调用setW。

cout << setw(5) << "Four" << " of " << "Hearts" << endl;
cout << setw(5) << "Queen" << " of " << "Diamonds" << endl;

显然,用变量替换了硬编码的字符串。

如果您知道最大场宽度(在这种情况下为5),则确实可以使用setw将第一个单词粘贴到该宽度:

#include <iostream>
#include <iomanip>
std::cout << std::setw(5) << card.value << " of " << card.suit << std::endl;

还有其他可能感兴趣的操作器,例如setfill来指定要填充填充填充的字符,以及leftright来指定要填充的字段的哪一侧。