如何在字符串中添加int

blo*_*ood 5 c++ string

我有一个字符串,我需要添加一个数字,即一个int.喜欢:

string number1 = ("dfg");
int number2 = 123;
number1 += number2;
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

name = root_enter;             // pull name from another string.
size_t sz;
sz = name.size();              //find the size of the string.

name.resize (sz + 5, account); // add the account number.
cout << name;                  //test the string.
Run Code Online (Sandbox Code Playgroud)

这工作...有点但我只得到"*名称*88888"和......我不知道为什么.我只需要一种方法将int的值添加到字符串的末尾

dir*_*tly 5

没有内置的运营商可以做到这一点.你可以编写自己的函数,operator+为a string和a 重载int.如果您使用自定义功能,请尝试使用stringstream:

string addi2str(string const& instr, int v) {
 stringstream s(instr);
 s << v;
 return s.str();
}
Run Code Online (Sandbox Code Playgroud)


Ber*_*ron 4

使用字符串流

#include <iostream>
#include <sstream>
using namespace std;

int main () {
  int a = 30;
  stringstream ss(stringstream::in | stringstream::out);

  ss << "hello world";
  ss << '\n';
  ss << a;

  cout << ss.str() << '\n';

  return 0;
}
Run Code Online (Sandbox Code Playgroud)