Use std::accumulate
(because you're accumulating a product of elements, so it makes the intent clear) and recall that '0'
is not 0, but that the digit characters are contiguous. For example, in ASCII, '0'
is 48, '1'
is 49, etc. Therefore, subtracting '0'
will convert that character (if it's a digit) to the appropriate numerical value.
int product = std::accumulate(std::begin(s), std::end(s), 1,
[](int total, char c) {return total * (c - '0');}
);
If you can't use C++11, it's easily replaced:
int multiplyCharacterDigit(int total, char c) {
return total * (c - '0');
}
...
int product = std::accumulate(s.begin(), s.end(), 1, multiplyCharacterDigit);
If neither of those are an option, what you had is almost there:
int product = 1;
for(int i = 0; i<myS.length(); i++)
product *= (myS[i] - '0');