1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <iostream>
int main()
{
using namespace std;
int a;
cout << "Give me an 8-digit integer.\n";
cin >> a;
// make sure it's in the right range
if((a>=100000000) || (a<10000000))
cout << "I asked for an 8 digit integer."
<< " Program will now terminate itself." << endl;
else // if this executes, there is a good 8-digit value
for (int i=10000000; i>0; i/=10)
{
cout << a / i << " ";
a%=i;
}
cout << endl;
return 0;
}
|
Sample output:
Give me an 8-digit integer.
12345678
1 2 3 4 5 6 7 8
How it works:
If you have an 8 digit integer MYINT, then integer math says that your integer divided by 10000000 is the first digit of MYINT.
Example:
12345678 / 10000000 = "1"
Similarly:
12345678 / 1000 = "12345"
Also
12345678 / 10 = "1234567"
After you output the digit you're interested in, you can throw it away. You do that with the modulus operator: "%"
12345678 % 10000000 = 2345678
We start out with "i = 10000000"
We divide "a" by "i" to get "1"
We MOD "a" by "i" to get "2345678"
Then, we divide "i" by 10, to remove one "tens" place, so 10000000 becomes 1000000
And the FOR loops keeps doing that until there are no more digits.
So the next iteration of the loop:
i = 1000000
a = 2345678
a / i = 2
a % i = 345678
i / 10 = 100000