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
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.
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.
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.
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>.
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();
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With