Output digits of a number This is a simple C++ program I had to write for class. It prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. How do I improve this? 

For example:




Input: 3456
Output: 
3 4 5 6
Sum of all digits: 19

Input: 1234
Output:
1 2 3 4
Sum of all digits: 10





#include &lt;iostream&gt;
#include &lt;iomanip&gt;

using namespace std;
int main()
{
    int base;
    int first;
    int second;
    int third;
    int fourth;
    int sum;

    cout &lt;&lt; " Please enter a whole number." &lt;&lt; endl;
    cin &gt;&gt; base ;

    first = base / 1000;
    second = base / 100 % 10;
    third =  base / 10 % 10;
    fourth = base % 10;

    sum = first + second + third + fourth;

    cout &lt;&lt; first &lt;&lt; " " &lt;&lt; second &lt;&lt; " " &lt;&lt; third&lt;&lt;  " " &lt;&lt; fourth &lt;&lt;  " " &lt;&lt; endl;
    cout &lt;&lt; "Sum of the digits: " &lt;&lt; sum &lt;&lt; endl;

    return 0;
}
Please stop using using namespace std. Read
this
Consider using a std::vector to hold the digits of a number. Here
it seems as though you can assume the user is inputting a number
with four digits. But that might not always be the case. A vector is
dynamic.
 This is...uh, well:

first = base / 1000;
second = base / 100 % 10;
third =  base / 10 % 10;
fourth = base % 10;


Consider using a while loop to get all digits of the number.

while(number)
{
    digits.push_back(number%10);
    number /= 10;
}


Note the digits will be in reverse. You can use std::reverse() to
reverse the digits such that the first element in the vector is the
first digit of the number.
Use std::accumulate() to obtain the sum of all digits. You don't
have to do this in the while loop.


Here is everything together. Ideally, you would want to put the while loop and summing operation in another function.

#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;algorithm&gt;

using std::cout;
using std::cin;
using std::endl;
using std::vector;



int main()
{
    int number, sum;
    vector&lt;int&gt; digits;

    cout &lt;&lt; "Enter a whole number: ";
    cin &gt;&gt; number;

    while(number)
    {
        digits.push_back(number%10);
        number /= 10;
    }


    std::reverse(digits.begin(),digits.end());
    sum = std::accumulate(digits.begin(),digits.end(),0);

    //C++11 range-based for loop
    for(auto i : digits)
        cout &lt;&lt; i &lt;&lt; " ";

    cout &lt;&lt; "\nSum of the digits: ";
    cout &lt;&lt; sum &lt;&lt; endl;

}