Answer to Question #160231 in C++ for Rohan

Question #160231

Write a program that prompts the user to input a 4 digit integer value and then outputs both the individual digits of the number and the sum of the digits.


1
Expert's answer
2021-02-02T10:34:19-0500

(Repeat)

This code solves your problem, it reads a line from the console, then checks that it consists only of digits and its length is 4. If something is entered incorrectly, an error will be displayed in the console. If everything is entered correctly, the digits will be displayed separately and the sum of these digits.

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

bool is_digits(const std::string &str) // Test a string for only numeric characters.
{
    return all_of(str.begin(), str.end(), ::isdigit);
}

int main()
{
    string s = "";
    int sum = 0;
    cout << "Input a 4 digit integer value" << endl;
    cin >> s;
    if (s.length() != 4 || is_digits(s) == false) {
        cout << "Invalide input" << endl;
        return 0;
    }
    cout << "Individual digits:";
    for (auto i : s) {
        sum += i - '0';
        cout << ' ' << i;
    }
    cout << endl << "Sum of numerals: " << sum << endl;
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog