Problem with finding exact int in array.

I'm trying to do a basic login system. The problem is, the first int in the array works just fine, but when I use any other one, it doesn't work.

CODE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{
	int Keys[]{ 123, 456, 789 };
	int key;
	bool isNumberMatched{ false };

	std::cout << ("Please Enter Key: ");
	std::cin >> key;

	for (auto keyy : Keys)
	{
		if (key == keyy)
		{
			//Do something
		}
		else
		{
			//Don't do something
		}
	}
}
Last edited on
Seems fine to me.
http://cpp.sh/6tup
Please Enter Key: 456
Nope, keep looking
Success
 
Is there a reason why it's saying it's wrong at first then it's correct? Can I avoid it?
EDIT: I understand why because it's searching through, but can I have it so it automatically jumps to it instead of slowly going through it?
Last edited on
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
int main()
{
	int Keys[]{ 123, 456, 789 };
	int key;
	bool isNumberMatched{ false };

	std::cout << ("Please Enter Key: ");
	std::cin >> key;

	bool ok = false;
	for (auto keyy : Keys)
	{
		if (key == keyy)
		{
			//Do something
			ok = true;
			break;
		}
		else
		{
			//Don't do something
		}
	}
	if(ok)
	  std::cout << "Okay";
	else  
	  std::cout << "Wrong";
}
That worked exactly to how I wanted it to! Thank you very much coder777
Why not just use std::find?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <algorithm>
#include <iostream>

int main()
{
	const int Keys[] {123, 456, 789};

	std::cout << ("Please Enter Key: ");

	int key;
	const bool ok = !!(std::cin >> key) && (std::find(std::begin(Keys), std::end(Keys), key) != std::end(Keys));

	if (ok)
		std::cout << "Okay";
	else
		std::cout << "Wrong";
}


This also deals with non-numeric input.
I understand why because it's searching through, but can I have it so it automatically jumps to it instead of slowly going through it?

there are ways to find data with less work. If the array is or can be sorted, you can binary search it, which greatly reduces work needed (20 iterations searches a million items), as one idea (but sorting does cost a lot of work, so you need to look for values several times to make it a net gain).
Topic archived. No new replies allowed.