-1

I came up with a non-standard way to convert numbers to strings. But the string only accommodates as much digits as the number of spaces I initialize it with. How to initialize it properly to contain as much digits as I require?

using namespace std;

string numbertostring(int n)
{
    int size=0;
    string number="            ";
    while(n)
    {
      number[size]=n%10+'0';
      size++;
      n/=10;
    }
    int i,j;
    for(i=0,j=size-1;i<j;++i,--j)
    swap(number[i],number[j]);
    return number;
} 

int main()
{
    cout<<numbertostring(1234)<<endl;
    return 0;
}
novice
  • 17
  • 3
  • just use [`to_string`](http://en.cppreference.com/w/cpp/string/basic_string/to_string) – NathanOliver Dec 16 '16 at 17:12
  • the number of digits consumed by an integer is proportional to its log in the base being used to write it. Also, string has a push_back method. – jaggedSpire Dec 16 '16 at 17:14
  • Anubhav, I voted to close because the question in your title, "How to convert a number to string in c++?", duplicates an existing question. However, if your real question was the one in the text, "How to initialize it properly to contain as much digits as I required", please say so, and I will vote to reopen. – Robᵩ Dec 16 '16 at 17:16
  • @Robᵩ i changed it – novice Dec 16 '16 at 17:27

1 Answers1

1

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);
}
Robᵩ
  • 163,533
  • 20
  • 239
  • 308