版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/CV2017/article/details/85336360
实现代码
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "ditong";
cout << str + to_string(5) << endl;
}
输出结果:ditong5
主要是用 to_string 函数 实现将数字转换为等形式的字符串形式,然后通过 + 号与另一个字符串拼接
常见错误
直接用 + 连接字符串和数字
string str = "ditong";
str + 5; // + 在此处不能起到连接作用,没有这种形式的重载用法
用 += 连接字符串和数字
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "ditong";
str += 5; //会将 int 转为 char 再连接上
cout << str << endl;
}
输出结果:
数字 5 转换成 ASCII 码表中的对应信息了