C++ iomanip table格式化
c++ iomanip table formatting
我遇到了 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();
}
我会打印一个格式正确的 table,但我的输出对齐不正确。简单来说,当我 cout
我的狗时,setw
和 setfill
只对 dog.name 起作用(因为 operator<<
的性质),结果是这样的
INFO AVAILABLE
linus , 10yoyes
而不是
INFO AVAILABLE
linus, 10 yo yes
显然我可以修改 operator<<
,仅将一个 string
附加到 os
,但在我的真实情况下,我必须更改大量复杂的定义(我更愿意避免此类更改! :D)
有什么想法吗?
setw
操纵器设置 next 输出的字段宽度,在本例中为 dog.name
。想在重载函数中直接使用流,实在没办法。
我遇到了 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();
}
我会打印一个格式正确的 table,但我的输出对齐不正确。简单来说,当我 cout
我的狗时,setw
和 setfill
只对 dog.name 起作用(因为 operator<<
的性质),结果是这样的
INFO AVAILABLE
linus , 10yoyes
而不是
INFO AVAILABLE
linus, 10 yo yes
显然我可以修改 operator<<
,仅将一个 string
附加到 os
,但在我的真实情况下,我必须更改大量复杂的定义(我更愿意避免此类更改! :D)
有什么想法吗?
setw
操纵器设置 next 输出的字段宽度,在本例中为 dog.name
。想在重载函数中直接使用流,实在没办法。