Recursive function to get a string to int

So i'm trying to recursively create a function that takes a string such as "1234" and return it as an integer such as 1234. I can not use any libraries or the such for this assignment. I have it sort of working however when I test for "36" I get 20 back instead and I am completely stuck on it


#include <iostream>
#include <math.h>
//-->>>>>
//--> it checks for aeiou, returns false for reverse, does not recognize it with other
//--> letters though
//-->>>>>>>>>>>>

int str2int(const char *mystr){
int len = 0;
int sum = 0;
int negative = 0;

if(mystr[0] == '\0'){
return 0;
}

for(int i = 0; mystr[i]; i ++){
len++;
std::cout<<len<<std::endl;
}
int i = 0;
if(mystr[i] < 48 || mystr[i] > 58){
return 0;
} else{
//sum = sum*10;
return (mystr[0] - 48) + pow(10,(len-1)) + str2int(mystr + 1);
}

}
Last edited on
Lets test your code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <cmath>

int str2int(const char *mystr) {
  int len = 0;
  int sum = 0; // warning: unused variable
  int negative = 0; // warning: unused variable

  if ( mystr[0] == '\0'){
    return 0;
  }

  for ( int i = 0; mystr[i]; i ++){
    len++;
  }

  int i = 0;
  if (mystr[i] < 48 || mystr[i] > 58){
    return 0;
  }else{
    int C = str2int(mystr + 1);
    std::cout << "A: " << mystr[0] - 48;
    std::cout << " B: " << pow(10,(len-1));
    std::cout << " C: " << C << '\n';
    return (mystr[0] - 48) + pow(10,(len-1)) + C;
  }

} 
int main()
{
  std::cout << str2int( "36" ) << "\n\n";
  std::cout << str2int( "1034" ) << "\n\n";
  std::cout << str2int( "0" ) << "\n\n";
  std::cout << str2int( "" ) << "\n\n";
}

A: 6 B: 1 C: 0
A: 3 B: 10 C: 7
20

A: 4 B: 1 C: 0
A: 3 B: 10 C: 5
A: 0 B: 100 C: 18
A: 1 B: 1000 C: 118
1119

A: 0 B: 1 C: 0
1

0

Does that output help you spot the source of error?
I believe I found my error that say if I put 20 in, I get the two back but it is not returning the 0, I am currently trying to see how I can get the zero but I am also stuck on that as well
You must have changed something for your posted code returns:
"20" => 2+10+0+1+0 == 13

Similarly:
"9000" => 9+1000+0+100+0+10+0+1+0 == 1120


What do you believe to have been the initial error?
Registered users can post here. Sign in or register to post.