Help with a vertical output question

Mar 24, 2017 at 1:14am
closed account (N0M9z8AR)
Write a program that takes a non-negative long as input and displays each of the digits on a
separate line. The program output should look similar to:
Enter an integer: 71345
7
1
3
4
5

can someone help and explain to me how to do this question, I have no idea where to start.

Thank you
Mar 24, 2017 at 2:34am
1
2
3
4
5
6
7
8
9
10
11
12
13
void print_vertical( unsigned long long n )
{
    if( n > 0 ) // if at least one digit is left
    {
        if( n < 10 ) std::cout << n << '\n' ; // only one digit, print it on a line by itself

        else // n has more than one digit
        {
            print_vertical( n/10 ) ; // print the more significant (left-most) digits first
            std::cout << n%10 << '\n' ; // and after that, print the last digit on a line by itself
        }
    }
}

http://coliru.stacked-crooked.com/a/494939ff1be5a440
Mar 24, 2017 at 10:03am
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>
#include <string>
using namespace std;

string vertical( unsigned long n )
{
   const string digits = "0123456789", newline = "\n";
   string vert;
   while( n > 0 )
   {
      vert = digits[n%10] + newline + vert;
      n /= 10;
   }
   return vert;
}


int main()
{
   unsigned long n;
   cout << "Enter an integer: ";   cin >> n;
   cout << vertical( n );
}


Input n: 71345
7
1
3
4
5




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

void vertical( unsigned long n )
{
   stringstream ss;
   ss << n;
   string s = ss.str();
   for ( char c : s ) cout << c << '\n';
}

int main()
{
   unsigned long n;
   cout << "Enter an integer: ";   cin >> n;
   vertical( n );
}
Last edited on Mar 24, 2017 at 11:02am
Mar 24, 2017 at 3:33pm
If std::string is used:
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <string>

int main()
{
    unsigned int number ;
    std::cin >> number ;
    for( char digit : std::to_string(number) ) std::cout << digit << '\n' ;
}

http://coliru.stacked-crooked.com/a/9b7a6d48ad49f57c

Mar 24, 2017 at 3:54pm
closed account (48T7M4Gy)
A small emebellishment

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <string>

int main()
{
    unsigned int number ;
    std::cin >> number ;
    for( auto i : std::to_string(number) ) std::cout << i << '\n' ;
}

1234567
1
2
3
4
5
6
7
 
Exit code: 0 (normal program termination)
Topic archived. No new replies allowed.