質問

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.

役に立ちましたか?

解決

You can use:

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

Does a char to digit conversion by ASCII character positions.

他のヒント

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.

std::atoi takes a const char*(a null terminated sequence of characters)

Try to change like

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

You are supplying with a single char hence the compiler is complaining

str[i] is char not char *

Use following :-

int x;
std::string str = "12345";
int a[5];
for(int i = 0; i < 5; i++)
{
    a[i] = str[i] -'0' ; // simply subtract 48 from char
}
x = a[0]*a[1]*a[2]*a[3]*a[4];
std::cout<<x<<std::endl;

look at this way

string str = "12345";
int value = atoistr.c_str());
// then do calculation an value in a loop
int temp=1;    
while(value){
    temp *= (value%10);
    value/=10;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top