Sum of Digits in a String

The instructions:
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 single 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. The program should also display the highest digit in the string.

Question: How would I be able to get the total properly? Number is always around 200 for the total whenever I try it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>
using namespace std;

int main()
{
	const int LENGTH = 100;
	char digits[LENGTH];
	int total = 0;
	cout << "Enter a series of digits with no spaces between them: ";
	cin >> digits;
	for (int j=0; j < strlen(digits); j++)
	{
		while (!isdigit(digits[j]))
		{
			cout << "One of the numbers you have inputted is not a digit." << endl;
			cout << "Please try again." << endl;
			cin >> digits;
		}
	}
	for (int index = 0; index < strlen(digits); index++)
	{
		total += digits[index];
	}
	cout << "The sum of those digits is " << total << "." << endl;
	char max = digits[0];
	for (int i = 0; i < strlen(digits); i++)
	{
		if (digits[i] > max)
		{
			max = digits[i];
		}
	}
	cout << "The highest digit is " << max << endl;
	return 0;
}
Think about type conversion! digits[index] is of type char while total is of type int.
Last edited on
As tcs mentioned it's a char. To convert simply subtract '0'
Topic archived. No new replies allowed.