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

1
  • "i don't know why". The second parameter to resize is a char, and resize uses it repeatedly to fill in any extra space it creates at the end of the string. In your case account is equal to 56 (mod 256), so you've passed the character 8. Commented Mar 7, 2010 at 2:22

5 Answers 5

5

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(); } 
Sign up to request clarification or add additional context in comments.

1 Comment

"There are no in-built operators that do this." I am disappoint. Oh well, I guess they couldn't think of everything...
4

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

Comments

4

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

Comments

1

Use a stringstream.

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

1 Comment

or use ostringstream to be precise.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.