if I have an integer (int i), and I want to append it to the end of a string expression, does this work:
string str = "number_is_" + i;
so that the desired value of str is
number_is_1
Printable View
if I have an integer (int i), and I want to append it to the end of a string expression, does this work:
string str = "number_is_" + i;
so that the desired value of str is
number_is_1
you have to convert the integer to a string first. Check out the atoi function.
atoi converts a string to an integer. I think what lisa188 wants is an integer to a string
This method is not very efficient. It is just the C++ version of sprintf. It depends on which version of IO stream you are using. There is the pre-STL version and the STL version.
If you are using the STL version,
ostringstream catted;
catted << "number_is_" << i;
// the result is in catted.str (). This is a string
If you are using the pre-STL version
ostrstream catted;
catted << "number_is_" << i;
// the result is in catted.str (). This is a const char*.
// once you access it, you are responsible for deleting it.
Here are two more possiblities:
char buf[16];
sprintf(buf,"%d", i);
string str = "number_is_" + buf;
or
char buf[32];
sprintf(buf,"number_is_%d", i);
string str = buf;
great; these things all work. Thanks!