Quick background: I'm working on Project Euler and made a palindrome checker. I needed to convert integers to strings. itoa() kept giving random values (9 gave 9 or 90, etc...), so I decided to make my own, and ran into a problem. I have fixed it, but could somebody explain what caused the problem and why the fix works?
Broken Code: The below code creates a stringstream inputs the number then puts that into a string and then into a char. The problem is it would chop the last number off when returning the char. (The buffer holds the 99800 value but the receiving variable numaschar = strItoA(num);
becomes 9980.)
char* strItoA(int number)
{
std::ostringstream sin;
sin << number;
std::string val = sin.str();
size_t length;
char buffer[val.size()+1]; //add one for the zero terminator
length=val.copy(buffer,val.length(),0); //do the transfer and grab the last position
buffer[length]='\0'; //zero terminate!!
return buffer;
}
The Fix:
char* buffer; //moved outside of function and given reference
char* strItoA(int number)
{
//Same...
buffer = new char [val.size()+1]; //added to keep buffer dynamic
//char buffer[val.size()+1]; //removed
//Same...
}
Thanks. :)