Integer problem

I need a program to be able to take in an integer 4 digits long, made up of only 1 and 0. However, integers will ignore the 0 if it is in the front, for example, 0110 comes out as 110. How am I able to pass each digit correctly without changing the initial input type, which is an int?
An int array comes immediately to mind, not sure if that solves your problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
	int arrayname [4] = {0,1,1,0};
	for (int i=0; i<4; i++)
	{
	cout << arrayname [i];
	}
	cin.ignore().get();
	return 0;
}
Yes. Take the entered integer and split it into digits with % and / operators. Then put them into array and pass that array to whatever function you need.
However note that 110 = 0110. The 0 is not lost, it's just not printed. 110/1000 is still 0. You may not need to use array as long as your function knows that there are 4 digits.
Alright, so how would I get a function/procedure to look at each digit individually, despite the number sequence being stored on a single variable? I need to be able to compare an entered sequence of 0s and 1s to one that is randomly generated. Basically, I need the program to recognize when they match, and keep generating random sequences til they do.
This is probably not what your after...

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

int main ()
{
	srand (time (NULL));
	int userarray [4];  
	int randomarray [4];  
	int digit, i, j;

	for (j=0; j<4; j++)
	{
		cout<<"Enter a binary digit (0 or 1).\n"; 
		cin >> digit;
		userarray [j] = digit;		
	}	 
   
	cout << "\n Randomly assigned binary digits are "; 
	for (i=0; i<4; i++)
	{
		randomarray [i] = (rand ()%2);  //randomly assigns a 1 or 0 to the array
		cout << randomarray [i];
	}	
  
 
	for (int c=0; c<4; c++)
		{
			if (randomarray[c] == userarray [c])
			{
				cout<<"\n\n\nBinary number "<< c+1 << " in the array is a match!!\n";
			}
			
		}
	

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