Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i add a int to a string

Tags:

c++

string

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

like image 777
blood Avatar asked Mar 06 '10 19:03

blood


People also ask

Can you have an int on a string?

The answer to your question is "no". A number can have one of several C types (e.g. int , double , ...), but only one of them, and string is not a numeric type.

Can you add an int to a string Java?

To concatenate a String and some integer values, you need to use the + operator. Let's say the following is the string. String str = "Demo Text"; Now, we will concatenate integer values.

How do you add an integer to a string in Python?

Method #2: Using %d operator This operator can be used to format the string to add the integer. The “d” represents that the datatype to be inserted to string is an integer.

How do I assign an int to a string in C++?

The next method in this list to convert int to string in C++ is by using the to_string() function. This function is used to convert not only the integer but numerical values of any data type into a string. The to_string() method is included in the header file of the class string, i.e., <string> or <cstring>.


2 Answers

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();
}
like image 192
dirkgently Avatar answered Oct 11 '22 19:10

dirkgently


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;
}
like image 44
Bertrand Marron Avatar answered Oct 11 '22 21:10

Bertrand Marron