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?
2 Answers
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.
2 Comments
Mike Vine
This has UB when
i == INT_MIN.JHBonarius
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.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
catnip
Problems if number <= 0. I would count the digits a different way.
JHBonarius
@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.
charand doing'0'+iper digit... i.e. using the char for 0 and adding an offset.