0

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?

11
  • Does this answer your question? Easiest way to convert int to string in C++ Commented Sep 10, 2020 at 19:42
  • 2
    please learn to use the search function of this site or Google. Commented Sep 10, 2020 at 19:43
  • 1
    One digit at a time? I would guess whoever gave you the assignment with the restrictions also gave some guidance on how to start. Commented Sep 10, 2020 at 19:43
  • 3
    you have a stupid teacher ( I hate teachers that act they are teaching you C++, but don't allow you to actual use C++.). you can try char and doing '0'+i per digit... i.e. using the char for 0 and adding an offset. Commented Sep 10, 2020 at 19:53
  • 1
    To be fair, I had to implement the equivalent manually once for a real-life program. Around 2005 or so. For underpowered cell phones. Commented Sep 10, 2020 at 20:02

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

This has UB when i == INT_MIN.
With teachers like his, iterators could as well be off limits, lol. Or std::string, and he'd want you to dynamically allocate a char array, hahaha.
1

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';
}

2 Comments

Problems if number <= 0. I would count the digits a different way.
@PaulSanders exercise for the reader ;) of course this is not the best solution. But it's not my assignment and i would just use to_string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.