如何将这些元素添加到字符串

时间:2019-04-12 21:08:01

标签: c++ string

我无法将这些元素添加到trans字符串中。 id为int,名称为string,成本,价格和利润均为double

我认为只使用'+'就可以了,但是我得到

  

“类型为'const char *'和'const char [8]'的无效操作数   二进制'operator +'

string transaction::toString(){
   string trans = "ID: " + getId() + ",Name: "+ getName()+ ",Cost: "+ getCost() + ", Price: "+getPrice() + ", Profit: "+getProfit();
   //trans += getId();
   return trans;
}

预期结果应如下所示: ID:(id值),名称:(名称字符串),成本:(成本值),价格:(价格值),利润:(利润值)

2 个答案:

答案 0 :(得分:3)

您可以添加#include <sstream>并执行以下操作:

string transaction::toString()
{
   stringstream ss;
   ss << "ID: " << getId() << ",Name: " << getName() << ",Cost: " << getCost()  << ", Price: " << getPrice()  << ", Profit: " << getProfit();
   return ss.str();
}

答案 1 :(得分:0)

您可以使用std::to_string()将所有非字符串转换为字符串。您需要导入库<string>

string trans = "ID: " + std::to_string(getId()) + ",Name: "+ getName()+ ",Cost: "+ std::to_string(getCost()) + ", Price: "+ std::to_string(getPrice()) + ", Profit: "+ std::to_string(getProfit()) ;