Split an Integer into its digits c++

后端 未结 12 1885
说谎
说谎 2020-11-28 15:27

I\'m trying to learn c++ on my own and I\'ve hit a bit of a road block. The problem is I need to take an integer,split it into its digits and get the sum of the digits and

12条回答
  •  臣服心动
    2020-11-28 16:15

    Your problem comes from the fact that you are reading the digits backwards, thus you need to print them out backwards. A stack will help you tremendously.

    #include "stdafx.h"
    #include 
    #include 
    #include 
    #include 
    
    int countDigitsInInteger(int n)
    {
        int count =0;
        while(n>0)
        {
            count++;
            n=n/10;
        }
        return count;
    }
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {  
        int intLength =0;
        int number;
        int digit;      
        int sum = 0;
        string s;    
        cout << "Please enter an integer ";
        cin >>number;
        cout << "Orginal Number = "< digitstack;
        while(number>0)
        {                         
            digit = number % 10;
            number = number / 10;
            digitstack.push(digit);
            sum = sum+digit; 
        }
    
        while(digitstack.size() > 0)
        {
            cout << digitstack.top() << " ";
            digitstack.pop();
        }
    
        cout <

    Oh, and BTW, keep your indentation clean. Its important.

    EDIT: In response to Steve Townsend, this method is not necessarily overkill, it is just different from yours. The code can be slimmed down so that it seems less like overkill:

    #include 
    #include 
    #include 
    
    using namespace std;
    
    int getInput(string prompt)
    {
        int val;
        cout << prompt;
        cin >> val;
        return val < 0 ? -val : val;
    }
    
    int main(int argc, char** argv)
    {
        int num = getInput("Enter a number: ");
        cout << "Original Number: " << num << endl;
    
        stack digits;
        int sum = 0;
        while(num > 0)
        {
            digits.push(num % 10);
            sum += digits.top();
            num = num / 10;
        }
    
        while(digits.size() > 0)
        {
            cout << digits.top() << " ";
            digits.pop();
        }
    
        cout << endl << "Sum of digits is " << sum << endl;
    
        return 0;
    }
    

提交回复
热议问题