Sum of digits in a string

This is an exercise for my Intro to CS class (not homework) that I am doing on my own. It asks to write a function "SumDigits", that takes a string as input and sums the values for each digit characters (0 through 9) and then returns the integer value for the sum.

Example: if the function is called with ("123") in main(), SumDigits should return 6(1+2+3).

All of my searches on the internet deal with getting a letter from a string and printing that out.

I only have to write the user-defined function and I keep getting 0 as my return value.

1
2
3
4
5
6
7
8
9
10
11
12
  int SumDigits (string strInput) { //get the string from main
      int index = 0; //initialize index position
      int sum = 0; //declare sum variable
      int strLen = (int)strInput.length(); //declare and initialize variable to hold the value of string length

      while (strInput[index] <= strLen){ 
             int str = strInput[index]; //declare int variable to hold value of string position
             sum = sum + 1;
      index ++;  //goes to the next position in the string
           }
      return sum;
}
Last edited on
You need to find a way to convert a char in your string to an int and sum them up.
1
2
char digit = '1';
int num = digit - '0'; // ==> num = 1 


Also it's much easier to use the Range-based for loop
1
2
3
4
5
string s("123");
for (char ch : s)
{
  // use ch
}
you should check each character of the string whether it is a digit or not and, indeed, if the string has any digits at all:
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
37
#include <iostream>
#include <string>
#include <cctype>
#include <sstream>

int arr[]={0,1,2,3,4,5,6,7,8,9};
//hard-coded, doesn't depend on ASCII, UTF etc

void sumString(const std::string& input)
{
    int sum{};
    bool match = false;
    for (const auto& elem : input)
    {
        if(isdigit(elem))
        {
            int temp = arr[elem - '0'];
            sum += temp;
            match = true;
        }
    }
    if(match == false)
    {
        std::cout << "No digits in the string \n";
    }
    else
    {
        std::cout << sum << '\n';
    }
}
int main()
{
    std::cout << "Enter input \n";
    std::string input{};
    getline(std::cin, input);
    sumString(input);
}
 
    while (strInput[index] <= strLen){ 

if the input string is "123" and index is 0 (first time) then the condition will evaluate as
 
    while ('1' <= 3)
and evaluated as an ASCII character, that results in
 
    while (49 <= 3)
which means the loop will never execute because the condition is false.

It should be
 
    while (index < strLen){ 

note < instead of <=.

I changed things up but now I'm getting 49 for SumDigis("123") instead of 0. The ASCII table reference makes sense but I'm still not seeing what I'm doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
int SumDigits (string strInput) {
    int index = 0;
    int sum = 0;
    int strLen = (int)strInput.length();
   
    while (index < strLen) {
            char character = strInput[index];
            int number = character;
            sum = number + sum;
    index ++;
    }
    return sum;
}
Last edited on
Got it to work!!!

I'm still a little perplexed at what EXACTLY is going on and if someone would maybe give me a step-by-step of each action, that would be a really helpful learning tool!

Thanks for all the help either way.

Here is the correct code (according to the machine my school uses):

1
2
3
4
5
6
7
8
9
10
11
12
13
14

int SumDigits (string strInput) {
    int index = 0;
    int sum = 0;
    int strLen = (int)strInput.length();
    
    while (index < strLen){
            sum = (strInput[index] - '0') + sum;
    index ++;
    }
    return sum;
}

a step-by-step of each action

Which part in particular are you uncertain about?

For example, the latest code differs from the earlier version in only one significant respect:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int SumDigits (string strInput) {
    int index = 0;
    int sum = 0;
    int strLen = (int)strInput.length();
   
    while (index < strLen) {
        char character = strInput[index];
        int number = character;
        number = number - '0';    // convert character code (ASCII) to integer
        sum = number + sum;
        index ++;
    }
    return sum;
}

that is to say, it is the conversion of the character which is encoded usually in ASCII (though other encoding systems exist), to a plain integer. It is dependent on the fact that the digits '0' to '9' are arranged in consecutive positions in the ASCII table.

The rest of the code is the mechanics of iterating through each character in the string - though it is a bit overly complex here. Taking the suggestion made earlier by Thomas1965, it could be reduced to this
1
2
3
4
5
6
7
8
9
10
11
int SumDigits (string strInput) 
{    
    int sum = 0;

    for (char ch : strInput)
    {
        sum += ch - '0';
    }
    
    return sum;
}



Or indeed using a more traditional for loop in place of the while loop:
1
2
3
4
5
6
7
8
9
10
11
int SumDigits (string strInput) 
{
    int sum = 0;
    
    for (unsigned int index = 0; index < strInput.length(); ++index)
    { 
        sum += strInput[index] - '0';
    }

    return sum;
}


If loops of different types are somewhat hard to understand, then it's worth reading through the tutorial page:
http://www.cplusplus.com/doc/tutorial/control/
@mongoliancowboy

Here's my version, added to the others. I'm using getline, in case the string inputted contains spaces.

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
#include <iostream>
#include <string>

using namespace std;

int SumDigits (string strInput);

int main()
{
	string strInput;
	int sum;
	cout << "Please a a line of numbers.. "<< endl;
	getline(cin, strInput); // Using getline, in case spaces are inputted as well
	sum = SumDigits(strInput);
	cout << "The total of the numbers entered, was " << sum << endl << endl;

	return 0;
}

int SumDigits (string strInput)
{ //get the string from main
	int x;
	int sum = 0; //declare sum variable
	int strLen = strInput.length(); //Variable to hold the value of string length

	for(x=0;x<strLen;x++)
	{
		if(strInput[x] <'0' || strInput[x]>'9') // Checking if the value is NOT a digit
			cout << strInput[x] << " is NOT a digit..." << endl;
		else // Otherwise
			sum+= strInput[x]-'0'; // Increase value of sum
	}
	return sum;
}
1
2
3
4
5
6
7
8
9
10
11
12
#include <string>
#include <algorithm>
#include <numeric>

// invariant: str contains only decimal digits
long long sum_digits( const std::string& str )
{
    if( str.find_first_not_of( "0123456789" ) != std::string::npos )
        throw std::invalid_argument( "badly formed string" ) ;

    return std::accumulate( str.begin(), str.end(), 0LL ) - str.size() * '0' ;
}
Last edited on
Topic archived. No new replies allowed.