The literal answer to your question is that the maxinum number of digits a integral type can hold is equal to this expression:
std::ceil(std::numeric_limits<TYPE>::digits10)
So your code would look like this:
std::string numbertostring(int n)
{
int size=0;
std::string number((std::size_t)std::ceil(std::numeric_limits<int>::digits10),
' ');
while(n)
{
number[size]=n%10+'0';
size++;
n/=10;
}
int i,j;
for(i=0,j=size-1;i<j;++i,--j)
std::swap(number[i],number[j]);
return number;
}
However, you don't need to initialize the string to the its maximum size. You can grow the string as required, using std::string::push_back
. This also means that the string keeps track of its own size, so you don't have to.
std::string numbertostring(int n)
{
std::string number;
while(n)
{
number.push_back(n%10+'0');
n/=10;
}
int i,j;
for(i=0,j=number.size()-1;i<j;++i,--j)
std::swap(number[i],number[j]);
return number;
}
Also, note that std::reverse()
exists:
std::string numbertostring(int n)
{
std::string number;
while(n)
{
number.push_back(n%10+'0');
n/=10;
}
std::reverse(number.begin(), number.end());
return number;
}
And, finally, std::to_string()
exists since C++11:
std::string numbertostring(int n)
{
return std::to_string(n);
}