0

i have a string of numbers, and i want to multiply these numbers

string myS = "731671765313";
int product = 1;
    for(int i = 0; i<myS.length(); i++)
        product *= myS[i];

How to convert the string element to int because the result is totally wrong. I tried casting it to int but in vain.

5
  • 1
    You can't just randomly "cast" an ASCII character to an integer and expect to get a number out of it! What you do think (int)'a' does? ;) Commented Feb 24, 2014 at 0:54
  • do you want to multiply all digits? then character to int conversion is (myS[i]-'0'), otherwise this is a duplicate and you should use std::stoi Commented Feb 24, 2014 at 0:55
  • I tried atoi(myS[i]) and stoi(myS[i]) ...... error Commented Feb 24, 2014 at 1:01
  • @CaptainObvlious, The question really seems to be about multiplying the digits in the string, not converting the string. The loop in the code makes this evident. Commented Feb 24, 2014 at 1:01
  • @chris I agree. Close vote retracted. Commented Feb 24, 2014 at 1:03

1 Answer 1

7

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');
Sign up to request clarification or add additional context in comments.

7 Comments

your solution requires a C++11-compliant implementation of the language, you should specify that.
@user2485710, As far as I'm aware, the C++ tag is C++11 by default, but I have made accommodations.
@Misaki, Is there a specific problem with either of the others besides one requiring C++11, or is it just that the last one is best suited to you? I didn't exactly test the second one, so if there's something wrong, I'd be glad to fix it.
"If you can't use C++", you forgot 11 ; by the way, like you, I wish that C++11 was more popular, but older C++ standards are still more popular than C++11.
@chris i think the last one is simpler than the others, no need to make it complicated. Besides i want to multiply certain elements from the string.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.