首页 > 解决方案 > 如何使用字符串流打印对齐的数据?

问题描述

我使用stringstream的每个数据都来自不同的类型,而不仅仅是int string.

#include <iostream>
#include <sstream>

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"
       << "day: "                   << day
       << " month: "                << month
       << " year: "                 << year
       << " name: "                 << name
       << " age: "                  << age                  << L"\n"
       << "height: "                << height
       << " weight: "               << weight
       << " height: "               << height
       << " price: "                << price
       << " count: "                << count                << L"\n"
       << "color: "                 << color
       << "time: "                  << time
       << "\n\n"; 
    
    std::cout << ss.str();
}

我如何对齐正在打印的数据?我试图实现的输出与此类似:

day:       monday          month:     february       year:      2000
name:      Natasha         age:       29             height:    169
weight:    63              price:     1000000        count:     1
color:     yellow          time:      13:06

-编辑-

我得到了更好的结果,但与预期相去甚远,其中:

    std::stringstream ss;
    ss << "\n-._,-'-._,-'-._,-'-._,-'\n"
       << "Data:\n"
       << "-._,-'-._,-'-._,-'-._,-'\n"
       << "day: "               << std::setw(12) << std::left  << day
       << " month: "            << std::setw(12) << std::left  << month
       << " year: "             << std::setw(12) << std::left  << year
       << " name: "             << std::setw(12) << std::left  << name
       << " age: "              << std::setw(12) << std::left  << age                  << L"\n"
       << "height: "            << std::setw(12) << std::left  << height
       << " weight: "           << std::setw(12) << std::left  << weight
       << " height: "           << std::setw(12) << std::left  << height
       << " price: "            << std::setw(12) << std::left  << price
       << " count: "            << std::setw(12) << std::left  << count                << L"\n"
       << "color: "             << std::setw(12) << std::left  << color
       << "time: "              << std::setw(12) << std::left  << time
       << "\n\n"; 

标签: c++windows

解决方案


推荐阅读