I_Burn
I_Burn

Reputation: 31

How to turn an int into a string?

I've been trying to find how to do it online. I'm restricted from not using ready-made functions, like to_string or boost::lexical_cast, not even the <sstream> library. How can I do it with these limitations?

Upvotes: 0

Views: 115

Answers (2)

catnip
catnip

Reputation: 25388

Here's one way to do it:

std::string int_to_string (int i)
{
    bool negative = i < 0;
    if (negative)
        i = -i;
    std::string s1;

    do
    {
        s1.push_back (i % 10 + '0');
        i /= 10;
    }
    while (i);
    
    std::string s2;
    if (negative)
        s2.push_back ('-');
    for (auto it = s1.rbegin (); it != s1.rend (); ++it)
        s2.push_back (*it);
    return s2;
}

I avoided using std::reverse, on the assumption that it would be off-limits.

Live demo

Upvotes: 2

JHBonarius
JHBonarius

Reputation: 11271

You can use '0' + i to get the char value of 0 and offset it. I.e.

#include <cmath>
#include <string>
#include <iostream>

int main() {
    int number = 12345678;

    int nrDigits = std::log10(number)+1;

    std::string output(nrDigits, '0'); // just some initialization

    for (int i = nrDigits - 1; i >= 0; i--) {
        output[i] += number % 10;
        number /= 10;
    }

    std::cout << "number is " << output << '\n';
}

Upvotes: 1

Related Questions