Separating Digits of an Integer

Hi, I'm trying to write a program that reads in 4 unknown digits and them outputs then like this:

Input: 3412
3 ***
4 ****
1 *
2 **

My code right now reads the inputs as one number and doesn't separate them. How would I do this without using arrays? Thanks to anyone that can help.


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
#include <iostream>
using namespace std;

//Global Constants

//Function Prototypes

//Execution Begins Here
int main(int argc, char** argv) {
  
  //Declare Variables
  int num1, num2, num3, num4;   
  
  //Displayed Text for User Input
  cout<<"Enter the first number: \n";
  cin>>num1,num2;
    
  //Loop and Initialization 
  for (int k=0; k<num1; k++) {
  cout<<"*";
 
  }
  for (int k=0; k<num2; k++) {
  cout<<"*";
 
  }
    
    return 0;
}
Last edited on
How about use cin 4 times ?
this is the general idea
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    cout << "Please enter an integer: ";
    int input = 0;
    cin >> input;



    while(input)
    {
        int temp = abs(input % 10);
        input /= 10;
        cout << temp << endl;
    }


    return 0;
}
I need to be able to read in all 4 digits and enter them in by only using the space bar once. Using cin 4 times would mean having 4 separate entries.
Read it into a string, and then use a for loop to go through the string checking each char.

That's how I'd do it at least. I think Yanson's idea looks better though.
Last edited on
Like this ? Well I'm bad with math
1
2
3
4
5
6
7
8
int x1, x2, x3,x4;
cout<<"enter 4 number wth space after 2 digit: "
cin>>x1;
cin>>x3;
x2=x1%10;
x1=(x1-x2)/10;
x4=x3%10;
x3=(x3-x4)/10;
an alternative approach
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    cout << "Please enter an integer: ";
    char temp = cin.get();

    while(temp != '\n')
    {
        if(isdigit(temp))
            cout << temp << endl;

        temp = cin.get();
    }

    cin.ignore();
    return 0;
}
Last edited on
Topic archived. No new replies allowed.