Trying to print one digit at a time using a specific algorithm

Im trying to print on digit at a time for example, 123 would be
1
2
3

using an algorithim my proffessor is telling us to use but mines ends up printing 123 as

1
12
123.


Any close on what to do?

My code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
  #include <iostream>
#include <math.h>
using namespace std;
void digit (int num)
{
    int num2 = num;
    int dc = 0;
    int x =0;
    int divisor = 0;
    
    {
            num=num/10;
            dc++;
    }
    divisor = pow(10, dc);
    
    
    while(dc < num)
    {
     num=num/10;
     dc++;
    }

       divisor = pow(10, dc);
       
       while(divisor > 0)
       {
           
           x = num2/divisor;
           
           cout << x << endl;
           
           x=x*divisor;
           
           x=num2-x;
           
           divisor=divisor/10;
          
       }
}
int main ()
{
    int num = 0;
    cout << "Please enter a number: ";
    cin >> num;
    
    digit(num);
    
    cin.ignore();
    cin.get();
    return 0;
}
Last edited on
Here is the link for the algorithm
https://pastebin.com/kBe9qiVH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>

int main()
{
   std::cout << "Enter an number: ";
   int num { };
   std::cin >> num;

   std::string num_str { std::to_string(num) };

   for (const auto& itr : num_str)
   {
      std::cout << itr << '\n';
   }
}
Enter an number: 123
1
2
3
number % 10 gets you the 1s place.

So if you combine % and /, you can get each digit (but this is actually backwards).

So it might be easier if you write a function to reverse the digits of an integer, then loop by printing (number % 10) then doing (number = number / 10) while number > 0.
Thanks Ganado!!! It works now :)
1
2
3
4
5
void print( unsigned long long number )
{
    std::cout << number << '\n' ;
    if( number > 9 ) print( number/10 ) ;
}

http://coliru.stacked-crooked.com/a/2c94fe5d49e44103
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

void print( unsigned long long n )
{
   if ( n > 9 ) print( n / 10 );
   std::cout << n % 10 << '\n';
}

int main()
{
   print( 1234567890112233ull );
}
1
2
3
4
5
6
7
8
9
0
1
1
2
2
3
3

But no, this is nothing like the (very longwinded) algorithm that your teacher required.
Last edited on
Here is the link for the algorithm


OMG - what are they teaching these days...
Topic archived. No new replies allowed.