Problem with finding exact int in array.

Sep 18, 2020 at 7:47am
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 Sep 18, 2020 at 7:48am
Sep 18, 2020 at 7:53am
Seems fine to me.
http://cpp.sh/6tup
Please Enter Key: 456
Nope, keep looking
Success
 
Sep 18, 2020 at 7:56am
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 Sep 18, 2020 at 7:59am
Sep 18, 2020 at 8:03am
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";
}
Sep 18, 2020 at 8:06am
That worked exactly to how I wanted it to! Thank you very much coder777
Sep 18, 2020 at 8:42am
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.
Sep 18, 2020 at 2:08pm
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).
Sep 20, 2020 at 12:46pm
Topic archived. No new replies allowed.