So I have finished the assignment however, I can't seem to wrap my head around another equivalent in c++ for to_string() inside string convertInteger(long n, int base) My error appears right at tostring()
Note that convertInteger() can be simplified. Consider:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
string convertInteger(long n, int base)
{
string str;
for (; n > 0; n /= base)
{
constint rem = n % base;
constchar digit = rem < 10 ? '0' + rem : 'a' + rem - 10;
str = digit + str;
}
if (str.empty())
str = "0";
return str;
}
It's usually a bad idea to do exact comparisons with float/double as the internal representation of a decimal using binary may not be exact. Normally a double/float test is for the value to be less than a specified constant (epsilon). Consider:
Note the initialisation of int_part. All assignments return the value of the assignment so fraction *= base returns the result of that assignment which is then in turn assigned to int_part.
Hello @Lastchance, i believe i made the mistake to double post , when i didn't know i could, I am still bright new to the website, so that is why i deleted them, THANKS :)
This is not a bad place for DIY code. The built in number to string and string to number stuff is all pretty sluggish, and rolling your own can be both educational and practical. But 99.99 % of code should use the built in ones or avoid the process. Only a very few things truly need it -- I did it about a year ago on an MD5 implementation and pulled it from 1.8 seconds per million inputs to .45 per million just by changing c++'s int to string to my own.
I found several websites on approaches to doing it various ways.