📌  相关文章
📜  国际空间研究组织 | ISRO CS 2008 |问题 33(1)

📅  最后修改于: 2023-12-03 15:23:02.581000             🧑  作者: Mango

ISRO CS 2008 | Question 33

This is a programming problem from the ISRO CS 2008 exam.

Problem Statement

Write a C++ program to read a string and find the sum of all digits in the string.

Input

The input consists of a single string which is at most 100 characters long.

Output

The program should output the sum of all digits found in the input string.

Example
Input
Hello123World456
Output
21
Solution

To solve this problem, we need to iterate through each character in the string and check if it is a digit. If it is a digit, we can convert it to an integer and add it to a sum variable.

Here's the C++ code to solve this problem:

#include <iostream>
#include <string>

int main() {
    std::string input;
    std::cin >> input;

    int sum = 0;
    for (char c : input) {
        if (isdigit(c)) {
            sum += c - '0';
        }
    }
    std::cout << sum << std::endl;

    return 0;
}

We first read the input string using std::cin. We then initialize a sum variable to 0 and loop through each character in the input string using a range-based for loop.

Inside the loop, we use the isdigit function to check if the current character is a digit. If it is, we subtract the ASCII code for '0' from the current character to get the integer value of the digit, and add it to the sum variable.

Finally, we output the value of sum using std::cout.