Reputation: 746
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
Upvotes: 5
Views: 4558
Reputation: 2825
you can use lexecal_cast
from boost, then C itoa
and of course stringstream
from STL
Upvotes: 0
Reputation: 99122
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));
Upvotes: 4
Reputation: 22220
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;
}
Upvotes: 4
Reputation: 347586
Use a stringstream.
int x = 29;
std::stringstream ss;
ss << "My age is: " << x << std::endl;
std::string str = ss.str();
Upvotes: 1
Reputation: 111316
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();
}
Upvotes: 5