Sum of digits in a string?

I have a question in my C++ class. Here it is:

Write a program that asks the user to enter a series of single-digit numbers with nothing separating them. Read the input as a C-string or a string object. The program should display the sum of all the isngle-digit numbers in the string. For example, if the user enters 2514, the program should display 12, which is the sum of 2, 5, 1, and 4.

I haven't started on it yet, but I just need help on how to actually do it. Do I make an int array, ask the user to enter a series of numbers, then use a loop to add all of the elements together? Or how?
You can get the C string, then use a loop and for each character of that string which is a digit add to a sum value the corresponding numeric value ( if you have '5' and you want to get 5 you can do it using '5'-'0' )
Last edited on
I made this simple program, & I think I'm doing it right, but I'm getting the wrong output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
int main()
{  
	const int LENGTH = 100;
	char bob[LENGTH];
	int total=0, index;
	cout << "Enter a series of numbers in a row " << endl;
	cin >> bob;
	for (index=0; index < LENGTH; index++)
	{
		total += bob[LENGTH];
	}
	cout << "The total is " << total << endl;
system("PAUSE");
return 0;
}



Enter a series of numbers in a row
1234
The total is -5200
Press any key to continue . . .

Of course the output should be 10, not -5200 lol.. what am I doing wrong??
You didn't enter LENGTH characters. Why loop through that many?

A std::string may be easier than a char[] here.
Here is the solution: (It's what Bazzy posted)

total += bob[LENGTH] - '0';
Last edited on
it should actually be total += bob[index] - '0';
and would be better using i < strlen( bob ) as breaking condition for the for loop
You'll get extra credit with us if your solution uses std::accumulate. :-)
It worked!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
int main()
{  
	const int LENGTH = 100;
	char bob[LENGTH];
	int total=0, index;
	cout << "Enter a series of numbers in a row " << endl;
	cin >> bob;
	for (index=0; index < strlen( bob ); index++)
	{
		total += bob[index] - '0';
	}
	cout << "The total is " << total << endl;
system("PAUSE");
return 0;
}


Enter a series of numbers in a row
123
The total is 6
Press any key to continue . . .

Thank you everyone!
Topic archived. No new replies allowed.