Click to See Complete Forum and Search --> : simple string concatenation question
lisa188
July 14th, 2002, 05:21 PM
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
Alexey B
July 14th, 2002, 05:32 PM
you have to convert the integer to a string first. Check out the atoi function.
cup
July 15th, 2002, 03:32 AM
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.
stober
July 15th, 2002, 04:19 AM
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;
lisa188
July 15th, 2002, 09:01 AM
great; these things all work. Thanks!
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.