Adding values from an array
May 21, 2013 at 5:00am UTC
How would one add each value from an array? I'm working from a string but I was wondering if there was a way to loop through the string and add each value. This is what I have so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
#include <cmath>
#include <string>
int main() {
std::string numbers;
int sum;
int count;
std::cout<< "Enter a series of numbers: " ;
std::cin>>numbers;
int iNumbers[numbers.length()];
for (int i = 0; i < numbers.length(); i++) {
for (int j = 0; j < numbers.length(); j++) {
numbers[i-0] = iNumbers[j];
}
while (sum < j) {
sum = iNumbers[j] + iNumbers[j + 1];
}
std::cout<< " Sum: " << sum;
}
}
Any thoughts/ideas?
May 21, 2013 at 6:35am UTC
I presume, you need to sum all digits in string.
1 2 3
unsigned sum(0);
for (char c: numbers)
sum += (c - '0' );
ot without C++11:
1 2 3
unsigned sum(0);
for (int i = 0; i < numbers.size(); ++i)
sum += numbers[i] - '0' ;
Last edited on May 21, 2013 at 6:36am UTC
May 21, 2013 at 10:35am UTC
i have no any IDEA....
May 21, 2013 at 10:46am UTC
1 2 3
#include <numeric>
int sum = std::accumulate( numbers.begin(), numbers.end(), 0,
[]( int acc, char c ) { return ( acc + c - '0' ); } );
Last edited on May 21, 2013 at 10:47am UTC
Topic archived. No new replies allowed.