I am making a project in C++, in which I need to make a login system. I wrote the code below, but I am not able to figure out why the password doesn't match when we run case 2 in the login()
function.
Core concept:
First, we need to register the user name and password, which is done in case 1 of the login()
function. Then, the user gets access to the information through his username and password.
Problem faced:
When I try to use a username and password of an already-registered user, the password doesn't match. I checked the stored password and entered password by printing them to the console, and they are the same. But, when we compare both by using the ==
operator, it gives a false result. Can anyone explain why?
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<conio.h>
using namespace std;
int login(void);
int main(void)
{
cout<<"Login system\n";
int d;
d = login();
if(d)
cout<<"Access granted!!"<<endl;
else
cout<<"Access denied!!"<<endl;
}
int login(void)
{
system("CLS");
cout<<"\n\n\n";
string username, password;
fstream file;
int choice;
again:
cout<<"1.Add new user\n2.login\n";
cin>>choice;
switch(choice)
{
case 1:
{
file.open("Login details.txt", ios :: app);
cout<<"Enter new username and password\n";
cin>>username;
cin>>password;
file<<username<<"\t\t";
file<<password<<endl;
return 1;
break;
}
case 2:
{
file.open("Login details.txt", ios :: in);
string tempname, temp_pass, k;
char temp_pas[100];
int p = 0;
cout<<"Enter your username and password\n";
cin>>tempname;
do
{
temp_pas[p] = getch();
if(temp_pas[p] != '\r')
cout<<"*";
p++;
}while(temp_pas[p - 1] != '\r');
cout<<endl;
for(int i = 0; i < p; i++)
{
temp_pass += temp_pas[i];
}
while(file)
{
file>>username;
file>>password;
cout<<q<<endl<<w<<endl;
if(tempname == username && temp_pass == password)
{
cout<<"access granted\n";
return 1;
}
}
cout<<"Invalid username or password\n";
return 0;
break;
}
default
{
cout<<"Choose a valid option"<<endl;
goto again;
}
}
}