Aiv
Aiv

Reputation: 21

How can I add up the values of the individual digits in a string?

I want to get the sum of the individual digits of an ID entered by the user. So far this is the code I have, and my code can count the number of characters in the user input but I'd like for it to also calculate the sum of the individual digits.

// user prompt for student id
cout << "Type in your student login ID: "; 

string studentId;

// user input of student ID
getline(cin, studentId); 

// computer output of studentId
cout << "Student ID Sum: " << studentId.length() << endl; 

Upvotes: 1

Views: 731

Answers (4)

Chris
Chris

Reputation: 36496

You can take advantage of std::accumulate from <numeric> for this purpose, iterating over the string s and adding the numeric value of each character to an accumulator if it's a digit.

#include <string>
#include <iostream>
#include <numeric>
#include <cctype>

int main() {
  std::string s = "456";

  std::cout << std::accumulate(
    s.begin(), s.end(), 0,
    [](unsigned int i, char &ch){ 
        return std::isdigit(ch) ? i + (ch - '0') : i; 
    }
  ) << std::endl;

  return 0;
}

Prints:

15

Upvotes: 1

Jitu DeRaps
Jitu DeRaps

Reputation: 144

You can also do with the help of input and output formatting.

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::string s = "2342";

    std::istringstream iss {s};
    std::ostringstream oss;

    // so that stream can look like : 2 3 4 2
    // adding whitespace after every number 
    for (char ch; iss >> ch;) {
        oss << ch << ' ';
    }

    std::string new_string = oss.str();
    std::istringstream new_iss {new_string};

    // read individual character of string as a integer using input      
    // formatting.
    int sum = 0;
    for (int n; new_iss >> n;) {
        sum += n;
    }

    std::cout << "sum :" << sum << '\n';
}

Upvotes: 0

khizer
khizer

Reputation: 1

read string character by character in for loop and covert character to integer by adding it to the sum

int sum =0;
for (int i=0; i< studentId.length(); i++){
    sum = sum  +  ((int)studentId[i] - 48);
}
cout<<sum;

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

Just use the range based for loop. As for example

unsigned int sum = 0;

for ( const auto &c : studentId )
{
    if ( '0' <= c && c <= '9' ) sum += c - '0';
}      

Upvotes: 5

Related Questions