Login system won't accept correct info after one failed attempt (while loop)

I am writing a simple login system utilizing a simple hash calculator to verify passwords inside of a class. The system asks for username and password if i enter user = 1 and password = "pass" the system lets me in however if my first attempt is wrong and i put in the right username and pass on the second attempt it will still fail. Help appreciated :)

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
#include <iostream>
#include <string>
#include "User.h"
using namespace std;
int x;

user users[10] = { { 4, 55, true }, { 4, 55, false }, { 4, 55, false }, { 4, 55, false }, { 4, 55, false }, { 4, 55, false }, { 4, 55, false }, { 4, 55, false }, { 4, 55, false }, { 4, 55, false } };


int hashCalc(string pass)
{
	// check hash of every char in string //
	for (int i = 0; i < pass.length(); i++)
	{
		// produce hash -96 from ascii to get place in alphabet //
		x = x + (pass[i] - 96);
	}
	return x;

}
int main()
{
	int attempts=0;

	while (attempts < 3)
	{
		int userIn;
		string passIn;
		cout << "Username:  ";
		cin >> userIn;
		cout << "Password:  ";
		cin >> passIn;

		if (hashCalc(passIn) == users[userIn].getHash())
		{
			cout << "Login Success!!!" << endl;
			cout << "User:  " << userIn << endl;
			cout << "Admin(y/n):  " << users[userIn].getAdmin() << endl;
			return 0;
		}
		else
		{
			cout << "Login fail try again. " << endl << endl;
			attempts = attempts + 1;
		}
	}
	cout << "GAME OVER MAN!" << endl;

}
Last edited on
Line 5: Why is x global? x should be a local variable within hashCalc() initialized to zero.

You get the correct hash calculation the first time because globals are guaranteed to be zero on program initialization. However, the second time you call hashCalc(), x contains the previous hash value, which you continue to add to. This is a perfect example of why global variables are bad.

Topic archived. No new replies allowed.