【发布时间】:2016-02-14 15:14:48
【问题描述】:
我遇到了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 我的狗时,setw 和 setfill 仅适用于 dog.name(因为 operator<< 的性质),结果类似于
INFO AVAILABLE
linus , 10yoyes
而不是
INFO AVAILABLE
linus, 10 yo yes
显然我可以修改operator<<,只将一个string 附加到os,但在我的实际情况中,我必须更改大量复杂的定义(我更愿意避免此类更改!:D)
有什么想法吗?
【问题讨论】: