simple Recursion atio issue

Just had a data structures class last semester... was working some exercises from the book in the chapter on recursion, and my code to "write a recursive function that converts a string to an int" does not give correct results... can't quite tell why... Any suggestions are appreciated

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

using namespace std;

int string2Int(string s, int* val)
{
int length = s.size();
string s2;
if( (length > 1) )
{
s2 = s.substr(1, length-1);

int temp = atoi((s.substr(0,1)).c_str());
temp *= (int)pow((double)10, (double)(length-1));
*val += temp;

return string2Int(s2, val);// Recursion
}
else
return *val += atoi(s.c_str());// if(length = 1), base case
}

int main()
{
int i = 0;
int* p = &i;
string s;

cout << "Enter a string to convert to int: ";
cin >> s;
cout << "\nInt is " << string2Int(s, p);
cin >> i;
return 0;
}
The problem is the pow function. It sometimes returns something like 9.999...
instead of 10, 99.999... instead of 100, etc... I suppose this would fix the problem:

temp *= (int)(pow((double)10, (double)(length-1))+0.5);
That was it! Thx Master Roshi, I haven't used pow() very much in my studies, but I was taught to be careful with those C-style casts...
You may be better off writing your own simple int pow function:
1
2
3
4
5
6
7
8
int pow(int b, int e)
{
   int ans = 1;
   for (int i = 0; i < e; ++i)
      ans *= b;

   return ans;
}


Since the cmath version is written for arbitrary floating point numbers (doubles), not integers.
Topic archived. No new replies allowed.