### output digits of an n number

Hello guys,
I have an problem with outputting all digits of an number. I know with 2, 3, 4, 5, 6 and so but i need to write all this code for lets say 3 digits.

 ``123456789101112131415161718`` `````` int main() { int a, b, c, d; a = 123; b = a % 10; a /= 10; c = a % 10; a /= 10; d = a % 10; cout << d << " " << c << " " << b << " "; return 0; } ``````

But can i somehow do this with a loop? And my question is what if n number was idk 123975234, how i can output all his digits with an loop, but not using 10000000 lines. Btw poor eng. Thanks :D :D :D

for(p10=10,i = 0; i < maxdigs; i++) //you can actually get max from a log call... log10(a)+1
{
cout << a% p10 << " ";
p10*=10;
}
cout << endl; //optional cleanup

Last edited on
Thanks, but that is too complicated to me, im beginner D:. Something simple?
well its also apparently wrong... oops !

for(i = 0; i < maxdigs; i++) //you can actually get max from a log call... log10(a)+1
{
cout << a% p10 << " ";
a /= 10;
}
cout << endl; //optional cleanup

that should do better. The earlier version would write 3, 23, 123 for 123...
this one should correctly do 3, 2, 1

it does not get much more simple, but ask about what you do not understand.
Last edited on
 ``123`` ``````#include void digits( unsigned long long n ) { if (n) std::cout << ( digits(n/10), n%10 ) << " "; } int main() { digits( 123975234 ); }``````
Last edited on
Topic archived. No new replies allowed.