Probably a commen question, but I can't find a good answer: how to convert an integer to a string?
I came across several solutions. I can't get stringstream to work. The function sprintf() gave problems to, and it's c-style. The function itoa() worked fine, but the reference says
This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.
And this function is c-style to.
I wrote my own c++-style function, and it works without problems:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
string convertInt(int number)
{
if (number == 0)
return"0";
string temp="";
string returnvalue="";
while (number>0)
{
temp+=number%10+48;
number/=10;
}
for (int i=0;i<temp.length();i++)
returnvalue+=temp[temp.length()-i-1];
return returnvalue;
}
Still, I would think there's a standard function (c++-style) available. If there isn't, can anyone give an example-code/link about how it's done stringstream?
string convertInt(int number)
{
stringstream ss;//create a stringstream
ss << number;//add number to the stream
return ss.str();//return a string with the contents of the stream
}
I didnt know about the memberfunctions str(). I tried the construction that is used when converting string to integer, but that didnt work. This works great.