-2

I am trying to split a number like 33245 into its digit 3,3,2,4,5 and adding them so the output is 17 but If I enter a char between them like 12m43 the output i get is 3. How may i check for the character here.I want "invalid input" as output. The problem is that it is not giving out any exception for char and that's why i am here.I have tried exception handling but it didn't worked since it is not generating any exception, i have omitted try and catch here, If it works at you please write that in comment box. Please help.Here is my code.

#include<iostream>
using namespace std;

int count(int n)
{
    int count=0;
    while(n>0)
    {
        n=n/10;
        count++;
    }
return count;
}


int main()
{
    int sum=0;
    int digit, t;
    int number;

    cin>>number;

    if(number<0)
    {
        number=-number;
    }
    digit=count(number);
    while(digit>0)
    {
        t=number%10;
        number=number/10;
        sum=sum+t;
        digit--;
    }
    cout<<sum<<endl;
    return 0;
}
Sameer Reza Khan
  • 474
  • 4
  • 15
  • 2
    TheformattingandindentationisincompleteandconfusingforexampleIcantquicklysewhaeremainstarts – Martin James Mar 05 '16 at 11:11
  • Possible duplicate of [How do I check if a C++ string is an int?](http://stackoverflow.com/questions/2844817/how-do-i-check-if-a-c-string-is-an-int) – Lajos Arpad Mar 05 '16 at 11:41
  • I think not, because here in this problem you have to enter a number like this 23451 or something like that. then the program will split each digit and add them up, then shows the result but if it founds any character after splitting it should return "invalid input" – Sameer Reza Khan Mar 05 '16 at 12:14

2 Answers2

2

1) Read data into string. This way you will read even non-digits and would be able to detect them.

2) Loop over characters of the string and check if all of them are digits. isdigit function from <cctype> will help you. You can use all_of algorithm from <algorithm> to avoid handwritten loop.

3) If everything is okay, loop over characters, transforming them into digits (c - '0' will get you digit from character) and adding result together. Use accumulate to avoid handwritten loops.

As requested: a short snippet

#include <algorithm>
#include <cmath>
#include <ctype.h>
#include <iostream>
#include <stdexcept>
#include <string>

bool is_number(const std::string& str)
{
    return std::all_of(str.begin(), str.end(), ::isdigit);
}

namespace detail
{
int digit_sum_unsafe(const std::string& str) //Avoids code duplication
{
    return std::accumulate(str.begin(), str.end(), 0, [](int sum, char c)
                               {
                                   return sum + (c - '0');
                               });
}
}

int digit_sum(const std::string& str)
{
    if(str[0] == '-') //Support for negative numbers
        str.erase(0, 1);
    if(not is_number(str)) //Proper exception handling
        throw std::domain_error("Not a number");
    return detail::digit_sum_unsafe(str);
}

template <typename T>
int digit_sum(T number) //Allows to use numbers without converting to string first
{
    std::string str = std::to_string(number);
    if(str[0] == '-')
        str.erase(0, 1);
    return detail::digit_sum_unsafe(str);
}

int main()
{   //Quick test
    std::string s;
    std::cin >> s;
    std::cout << digit_sum(s);
}
Revolver_Ocelot
  • 8,609
  • 3
  • 30
  • 48
0

Here's a very simple program that should get you going.

The program reads a string from standard input, checks whether it is a positive integer using is_number function, and then, if the string contains only digits, computes the sum of the digits on the standard output; otherwise it reports an error. You should be able to modify the code to suit your needs.

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

bool is_number(const std::string& input);

int main(int argc, char** argv) {
    std::string input;

    std::cout << "Enter a number." << std::endl;
    std::getline(std::cin, input); // You can use std::cin >> input; otherwise; depends on what you want.
    if (!is_number(input)) {
        std::cerr << "The input should be a string of digits." << std::endl;
        return -1;
    }

    int sum = 0;
    for (size_t i = 0; i < input.length(); ++i) {
        sum += (input[i] - '0');
    }
    std::cout << "The sum is " << sum << "." << std::endl;
    return 0;
}

bool is_number(const std::string& input) {
    size_t i;
    for (i = 0; i < input.length() && isdigit(input[i]); ++i)
        ;
    return i == input.length();
}
blazs
  • 4,705
  • 24
  • 38