c ++ iomanip表格式化

时间:2016-02-14 15:14:49

标签: c++ cout iomanip

我遇到了iomanip的问题。我认为简化的代码可以比文字更好地解释一切。

#include <iostream>
#include <iomanip>
#include <string>

struct Dog {
  std::string name;
  int age;
};

std::ostream& operator<<(std::ostream& os, Dog dog) {
  return os << dog.name << ", " << dog.age << "yo";
}

int main() {
  Dog dog;
  dog.name = "linus";
  dog.age = 10;

  std::cout
    << std::left << std::setw(20) << std::setfill(' ') << "INFO"
    << std::left << std::setw(20) << std::setfill(' ') << "AVAILABLE" << std::endl;

  std::cout
    << std::left << std::setw(20) << std::setfill(' ') << dog
    << std::left << std::setw(20) << std::setfill(' ') << "yes";

  std::cin.get();
}

我会打印格式良好的表格,但输出结果不对齐。简单来说,当我cout我的狗时,setwsetfill仅适用于dog.name(因为operator<<的性质),结果类似于

INFO                AVAILABLE
linus               , 10yoyes

而不是

INFO                AVAILABLE
linus, 10 yo        yes

显然我可以修改operator<<,只将string添加到os,但在我的实际情况下,我必须更改大量复杂的定义(我更喜欢避免这些更改!:D )

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

setw操纵器设置 next 输出的字段宽度,在本例中为dog.name。如果你想在重载函数中直接使用流,那么它真的没办法了。