Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Atoi function gives error [duplicate]

Tags:

c++

atoi

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.

like image 892
jason Avatar asked Feb 21 '26 01:02

jason


2 Answers

You can use:

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

Does a char to digit conversion by ASCII character positions.

like image 84
flavian Avatar answered Feb 23 '26 14:02

flavian


The proper way to do this is std::accumulate instead of rolling your own:

std::accumulate(std::begin(str), std::end(str), 1, [](int total, char c) {
    return total * (c - '0'); //could also decide what to do with non-digits
});

Here's a live sample for your viewing pleasure. It's worth noting that the standard guarantees that the digit characters will always be contiguous, so subtracting '0' from any of '0' to '9' will always give you the numerical value.

like image 37
chris Avatar answered Feb 23 '26 15:02

chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!