gpt4 book ai didi

c++ - 我如何将这些元素添加到字符串中

转载 作者:行者123 更新时间:2023-11-27 23:40:17 25 4
gpt4 key购买 nike

我在将这些元素添加到 trans 字符串时遇到了问题。 id是一个int,name是一个string,成本、价格和利润都是double

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

"invalid operands of types'const char*' and'const char[8]' to binary'operator+'

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

预期的结果应该是这样的:ID:(id值),Name:(名称字符串),Cost:(成本值),Price:(价格值),Profit:(利润值)

最佳答案

您可以添加 #include <sstream>并这样做:

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

关于c++ - 我如何将这些元素添加到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55659444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com