Super noob question...

I am very new to programming. I am trying to find each seperate digit of a 5 digit number in a sequence and then print each seperate number. Hopefully my code will explain better what I am trying to do. Any other ways to make this more efficient would also be nice. Thanks,

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

int main()
{
	string str = "Searching\n";
	char pass[5]; cin >> pass;
	int i[5]; i[0]=0; i[1]=0; i[2]=0; i[3]=0; i[4]=0;
		if (i[0]!=pass[0])
		{
			cout << str; ++i[0];
		}
			cout << "First # " << i[0] << "\n";
		if (i[1]!=pass[1])
		{
			cout << str; ++i[1];
		}
			cout << "Second # " << i[1] << "\n";
		if (i[2]!=pass[2])
		{
			cout  << str; ++i[2];
		}
			cout << "Third # " << i[2] << "\n";
		if (i[3]!=pass[3])
		{
			cout << str; ++i[3];
		}
	return 0;
}
1
2
	string str = "Searching\n";
	char pass[5]; cin >> pass;


Why are you using the dangerous C-string instead of a std::string?

If you try to enter 5 digits into your C-string you will overflow the array, a std::string would not have this problem. Remember a C-string must be terminated by the end of string character ('\0') so an array of size 5 only has room for 4 "digits" along with the end of string character.

You should also never try to get input into a C-string with a method that doesn't limit the number of characters it will try to retrieve. The extraction operator can be limited by using the setw() manipulator.
So I was able to get the results I wanted. This is the code I used to make it happen. There is probably an easier, more condensed way of doing it though.
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
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <string>
using namespace std;

int main()
{
	int i1=0; int i2=0; int i3=0; int i4=0; int i5=0;
	string b = "\n";
	string srch = "Searching\n";
	string s1 = "First # - ";
	string s2 = "Second # - ";
	string s3 = "Third # - ";
	string s4 = "Fourth # - ";
	string s5 = "Fifth # - ";
	string ps; cin >> ps;
	string psd = ps;
	while (i1!=psd[0])
	{
		++i1;
		if (i1==25)
		{
			cout << srch;
		}
	}
	cout << s1 << i1-48 << b;
	while (i2!=psd[1])
	{
		++i2;
		if (i2==25)
		{
			cout << srch;
		}
	}
	cout << s2 << i2-48 << b;
	while (i3!=psd[2])
	{
		++i3;
		if (i3==25)
		{
			cout << srch;
		}
	}
	cout << s3 << i3-48 << b;
	while (i4!=psd[3])
	{
		++i4;
		if (i4==25)
		{
			cout << srch;
		}
	}
	cout << s4 << i4-48 << b;
	while (i5!=psd[4])
	{
		++i5;
		if (i5==25)
		{
			cout << srch;
		}
	}
	cout << s5 << i5-48 << b;
	cout << psd;
	return 0;
}
Topic archived. No new replies allowed.