nik - 1 year ago 64

C++ Question

I have a function that supposed to compute sum and return integer result, but it doesn't return the right value because when I multiply by 2 it takes value from ASCII table, not the integer value.

This part of the code is correct:

sum += *(ptrISBN + i) - '0'

, but when i try to multiply it by 2 it gives me ANSCII output, can someone help me to convert it into integer value somehow?

`int checkSum(char *ptrISBN)`

{

int sum = 0;

for (int i = 0; i < 14; i++) {

if (isdigit(*(ptrISBN + i)))

sum += *(ptrISBN + i) - '0' * 2;

}

return sum;

}

Answer Source

Try:

```
int checkSum(char *ptrISBN)
{
int sum = 0;
for (int i = 0; i < 14; i++) {
if (isdigit(*(ptrISBN + i)))
sum += (*(ptrISBN + i) - '0') * 2; //little change here
}
return sum;
}
```

I assume You wanted to convert character ('0' to '9') to its int value and then multiply it by 2.
Without change You were doing `sum += *(ptrISBN + i) - ('0' * 2);`

which is not what You were looking for. That happened because multiplication was done before subtraction.