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.
cout << "Type in your student login ID: "; // user prompt for student id
string studentId;
getline(cin, studentId); // user input of student ID
cout << "Student ID Sum: " << studentId.length() << endl; // computer output of studentId
CodePudding user response:
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';
}
CodePudding user response:
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
CodePudding user response:
You can do calculate sum by using a for
loop.
#include <iostream>
using namespace std;
int main()
{
//Initializing variables.
char studentId[100];
int i,sum = 0;
getline(cin, studentId); //get user input here in array
//Iterating each character through for loop.
for (i= 0; studentId[i] != '\0'; i )
{
if ((studentId[i] >= '0') && (studentId[i] <= '9')) //Checking for numeric characters.
{
sum = (studentId[i] - '0'); //Adding numeric characters.
}
}
//Printing result.
cout<<"Sum of the studentId:"<< sum;
return 0;
}