0

I'm helping a friend with a C++ assignment. There is an issue with the folowing base converter function:

#include <iostream>
#include <cmath>
using namespace std;

int strToInt(string num, unsigned base){
    int result = 0;
    for (int i=0; i<num.length(); i++) {
        if (num[i]>='0' && num[i]<='9')
            result += (num[i]-'0')*pow(base,num.length()-i-1);
        else if (num[i]>='A' && num[i]<='F')
            result += (num[i]-'A'+10)*pow(base,num.length()-i-1);
        else if (num[i]>='a' && num[i]<='f')
            result += (num[i]-'a'+10)*pow(base,num.length()-i-1);
    }
    return result;
}

int main()
{
    string number;
    int base;
    while(number.compare("exit")!=0){
        cin>>number;
        cin>>base;
        cout<<strToInt(number,base)<<"\n\n";
    }
    return 0;
}

For some inexplicable reason every time I enter 3 and 5 digit decimals and chose base 10 I am getting the proper number -1.

E.g.

100
10
99

10000
10
9999

I've been going over this function for the last 5-6 hours and adding all types of debug code, but for the good of me I can't figure out what the hell is wrong.

Code style remarks are also very appreciated.

Cheers

Georgi
  • 165
  • 1
  • 9
  • @latedeveloper good point about the magic number. Much more readable. However I don't see any difference between == and compare(). What do you mean by testing the return value? Validation? That is not a requirement of the task. Thanks for the feedback. – Georgi Jan 21 '17 at 21:14
  • Did you try stepping through your code with a debugger? Debugger is **the** tool to use, when the code behaves incorrectly. – Algirdas Preidžius Jan 21 '17 at 21:15
  • 1
    I cannot reproduce; with your input I get 100-10-100 and 10000-10-10000 – Stephan Lechner Jan 21 '17 at 21:21
  • 1
    Do you use some very old compiler? Or a target platform with software emulated floating point? First suspect would be the rounding of the pow return value to int, but this works fine for me. – Ludwig Schulze Jan 21 '17 at 21:31
  • I am using mingw that comes with CodeBlocks. Won't be surprised if it's quite old. – Georgi Jan 21 '17 at 21:33

1 Answers1

2

std::pow does floating-point math. You're probably getting a round-off error somewhere. The usual way to accumulate values is to multiply and add each time through the loop:

result *= base;
result += ch - '0';
Pete Becker
  • 74,985
  • 8
  • 76
  • 165