|
From: Martin F. <mar...@gm...> - 2004-07-24 10:05:19
|
Hi,
> I'm trying to program a mehtod which returns an string. More or less it i=
s
> something like that:
> ...
> It doesn't work. I thought the "+" operator was going to convert the int
> values to strings in order perform de concatenation, but it seems this
> is not the way it works. How can I construct this string then?
No, it doesn't convert the int values into strings. It merely appends them =
as characters to the string.
Here is my example to implement what you tried:
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
string convert_int_array(int int_array[], int iCount)
{
/*original code
string sOutput;
for(int i=3D0; i<iCount; i++) {
sOutput +=3D int_array[i];
}
*/
// print array content into a output string stream
ostringstream out;
for(int i=3D0; i<iCount; i++) {
out << int_array[i] << " ";
}
return out.str();
}
int main()
{
int array[] =3D {1, 3, 5, 7, 11, 13, 17};
string str =3D convert_int_array(array, sizeof(array)/sizeof(int));
cout << str << endl;
return 0;
}
To format numeric values into a string representation using C++, you should=
use the stream classes. My example function first prints your integer valu=
es separated by space characters into a ostringstream object. After that it=
converts the stream buffer to a string object and returns that to be proce=
ssed further.
Regards,
Martin
|