如何使用C++ stringstream实现多类型数据的对齐打印?
解决方法
你只需要做两处核心调整即可实现预期对齐效果:
- 新增引入
<iomanip>头文件,std::setw、std::left等格式化控制符均定义在该头文件中,缺少引入会导致格式化逻辑不生效。 - 你之前的调整只给输出值设置了固定宽度,但
day:、month:这类键名本身长度不一致,会导致列偏移。正确的做法是给键名也设置固定的输出宽度,保证每一列的起始位置统一。
完整可运行代码
#include <iostream> #include <sstream> #include <iomanip> // 新增引入格式化头文件 int main() { std::string day = "monday"; std::string month = "february"; std::string year = "2000"; std::string name = "Natasha"; std::string age = "29"; std::string height = "169"; std::string weight = "63"; std::string price = "1000000"; std::string count = "1"; std::string color = "yellow"; std::string time = "13:06"; std::stringstream ss; ss << "\n-._,-'-._,-'-._,-'-._,-'\n" << "Data:\n" << "-._,-'-._,-'-._,-'-._,-'\n" // 每一组键名固定占8位左对齐,值固定占12位左对齐,保证总宽度一致 << std::left << std::setw(8) << "day:" << std::setw(12) << day << std::left << std::setw(8) << "month:" << std::setw(12) << month << std::left << std::setw(8) << "year:" << std::setw(12) << year << "\n" << std::left << std::setw(8) << "name:" << std::setw(12) << name << std::left << std::setw(8) << "age:" << std::setw(12) << age << std::left << std::setw(8) << "height:" << std::setw(12) << height << "\n" << std::left << std::setw(8) << "weight:" << std::setw(12) << weight << std::left << std::setw(8) << "price:" << std::setw(12) << price << std::left << std::setw(8) << "count:" << std::setw(12) << count << "\n" << std::left << std::setw(8) << "color:" << std::setw(12) << color << std::left << std::setw(8) << "time:" << std::setw(12) << time << "\n\n"; std::cout << ss.str(); return 0; }
输出效果
运行上述代码后输出完全符合你的预期:
-._,-'-._,-'-._,-'-._,-' Data: -._,-'-._,-'-._,-'-._,-' day: monday month: february year: 2000 name: Natasha age: 29 height: 169 weight: 63 price: 1000000 count: 1 color: yellow time: 13:06
如果想要和你示例的缩进完全匹配,调整std::setw的参数值即可,数值越大对应列的宽度越宽。
内容的提问来源于stack exchange,提问作者user16852409
相关产品推荐
相关产品推荐

