Search code examples
c++atoi

C++ Atoi function gives error


I have a string which has 5 characters. I want to convert each single character to int and then multiply them with each other. This is the code :

int main()
{
    int x;
    string str = "12345";
    int a[5];
    for(int i = 0; i < 5; i++)
    {
        a[i] = atoi(str[i]);
    }
    x = a[0]*a[1]*a[2]*a[3]*a[4];
    cout<<x<<endl;
}

It gives this error for the line with atoi :

invalid conversion from 'char' to 'const char*' [-fpermissive]|

How can I fix this? Thanks.


Solution

  • You can use:

    a[i] = str[i] - '0';

    Does a char to digit conversion by ASCII character positions.