Recursion - string to integer problem

here’s my code its giving segmentation fault.
#include
#include
#include
#include
#include
using namespace std;

int stringtoint(string str,int i)
{
if(i==(str.length()-1))
{
int i = str[i]-‘0’;
return i;
}
int sum = pow(10,str.length()-i-1) * (str[i]-‘0’) + stringtoint(str,i+1);
return sum;
}
int main() {
string str;
cin>>str;

int ans = stringtoint(str,0);
cout<<ans;
return 0;

}

and i also want to know why it was giving error when i was using atoi(str[i]) instead of str[i]-‘0’.
thanks

Hey, there is a mistake in your base case of stringtoint(). You have declared the variable i again in base case which results in wrong output. So, update your base case like this

if(i==(str.length()-1))
{
    int j = str[i]-'0';
    return j;
}

Hey, you atoi() take a string input and converts it to integer but atoi(str[i]) here you are passing a character to the function which results in an error.

But isn’t that stoi() function which converts string to integer.

Hy, basically the C function atoi() converts C-strings (null terminated character arrays) to an integer. The C++ stoi() converts the C++ string to an integer. Note that the atoi() function will silently fail if the string is not convertible to an int as it return 0 when there is some error, while by default stoi() will throw an exception.