How to add int string to string

I have a string and I need to add a number to it ie int. as:

string number1 = ("dfg");
int number2 = 123;
number1 += number2;

this is my code:

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.

this works ... somewhat, but I only get "* name * 88888" and ... I don't know why. I just need a way to add an int value to the end of the line

+5
source share
5 answers

Use stringstream .

#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;
}
+4
source

There are no built-in operators in this. You can write your own function, overload operator+for stringand int. If you are using a custom function, try using stringstream:

string addi2str(string const& instr, int v) {
 stringstream s(instr);
 s << v;
 return s.str();
}
+5
source

:

template<class T>
std::string to_string(const T& t) {
    std::ostringstream ss;
    ss << t;
    return ss.str();
}

// usage:
std::string s("foo");
s.append(to_string(12345));

, Boosts lexical_cast():

s.append(boost::lexical_cast<std::string>(12345));
+4

stringstream.

int x = 29;
std::stringstream ss;
ss << "My age is: " << x << std::endl;
std::string str = ss.str();
+1

you can use lexecal_castfrom boost, then C itoaand, of course, stringstreamfrom STL

0
source

All Articles