正在格式化流空间

Formatting stream spaces

本文关键字:空间 格式化      更新时间:2023-10-16

我一直在尝试使用.prushback来格式化我的字符串,以便它只在每个单词之间打印一个空格。

所以我尝试使用.push_back,但是它不适用于整数。

std::string FormatVehicleString(std::string year,
    std::string make,
    std::string model,
    double price,
    double mileage)
{
    year.push_back(5);
    make.push_back(5);
    model.push_back(5);
    price.push_back(5);
    mileage.push_back(5);
}

有人能给我指一个正确的方向吗?有没有其他的值类型可以包含字符串和整数?

一个选项是使用std::ostringstream

std::string FormatCarInfo(std::string year,
    std::string make,
    std::string model,
    double price,
    double mileage)
{
   std::ostingstream out;
   out << year << " ";
   out << make << " ";
   out << model << " ";
   out << price << " ";
   out << mileag ;
   return out.str();
}

另一种选择是使用std::to_string

std::string FormatCarInfo(std::string year,
    std::string make,
    std::string model,
    double price,
    double mileage)
{
   return ( year + " " + make + " " + model + " " + 
            std::to_string(price) + " " + std::to_string(mileage) );
}