如何将字符串和整数组合成单个字符串 (C++)

How to combine strings and ints to a single string (C++)

本文关键字:字符串 单个 C++ 整数 组合      更新时间:2023-10-16

可能的重复项:
C++连接字符串和整数

我正在尝试使用许多字符串和整数来制作单个字符串,但我收到消息:"错误 C2110:'+':无法添加两个指针"

这是我的代码:

transactions[0] = "New Account Made, Customer ID: " + ID + ", Customer Name : " + firstName + " " + secondName + endl + ", Account ID: " + setID + ", Account Name: " + setName;

(请注意,ID 和 setID 是一个整数)

使用字符串流:

#include <sstream>
...
std::stringstream stm;
stm<<"New Account Made, Customer ID: "<<ID<<", Customer Name : "<<firstName<<" "<<secondName<<std::endl<<", Account ID: "<<setID<<", Account Name: "<<setName;

然后,您可以使用 stm.str() 访问生成的字符串。

你应该使用字符串流:将字符串写入其中;然后写入 int。最后,通过流的str()方法收获结果:

stringstream ss;
string hello("hello");
int world = 1234;
ss << hello << world << endl;
string res = ss.str();
cout << res << endl;

这是关于 ideone 的演示的链接。