我和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<<,只在os中附加一个string,但在实际情况下,我必须更改大量复杂的定义(而且我更喜欢避免这样的更改!:D)
有什么想法吗?
发布于 2016-02-14 15:20:06
setw机械手设置下一个输出的字段宽度,在本例中是dog.name。如果您想直接在重载的函数中使用流,就没有办法绕过它。
https://stackoverflow.com/questions/35393334
复制相似问题