views:

127

answers:

5

i have a string and i need to add a number to it i.e a int. like:

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 the "*name*88888" and... i don't know why. i just need a way to add the value of a int to the end of a string

+5  A: 

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

string addi2str(string const& instr, int v) {
 stringstream s(instr);
 s << v;
 return s.str();
}
dirkgently
"There are no in-built operators that do this." I am disappoint. Oh well, I guess they couldn't think of *everything*...
Ignacio Vazquez-Abrams
+1  A: 

Use a stringstream.

int x = 29;
std::stringstream ss;
ss << "My age is: " << x << std::endl;
std::string str = ss.str();
Brian R. Bondy
or use ostringstream to be precise.
Dave18
+2  A: 

Use a 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;
}
Bertrand Marron
xD yay it works Tyvm
blood
+4  A: 

You can use string streams:

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));

Alternatively you can use utilities like Boosts lexical_cast():

s.append(boost::lexical_cast<std::string>(12345));
Georg Fritzsche
A: 

you can use lexecal_cast from boost, then C itoa and of course stringstream from STL

den bardadym