The primary indexes(usernames) are stored in “index.dat”. The user information is stored in “users.dat”
in the format “username|password” (e.g. “jack|qwerty123”). “Login()” is the
login function.
Code#include<iostream>
#include<string>
#include<fstream>
#include<list>
#include<map>
using namespacestd;
// filenames
conststring fnindex = "index.dat";
conststring fnusers = "users.dat";
// lists of usernamesand passwords
list<string>users;
map<string,string> passwords;
boolLoadUsernames() {
ifstream findex(fnindex);
string username;
// users are added to usernamelist
if (findex.is_open()) {
while (getline(findex,username)) {
users.push_back(username);
}
findex.close();
return true;
}
else {
return false;
}
}
boolLoadPasswords() {
ifstream fusers(fnusers);
string line;
string username;
string password;
// users with passwords are addedto username list
if (fusers.is_open()) {
while (getline(fusers,line)) {
intpos = line.find("|");
username =line.substr(0, pos);
password =line.substr(pos+ 1);
passwords.emplace(username,password);
}
fusers.close();
return true;
}
else {
return false;
}
}
// login function
voidLogin() {
list<string>::iteratorpos;
string username;
string password;
bool logged = false;
LoadUsernames();
while (!logged) {
cout << "Enterusername:" << endl;
cin >>username;
cout << "Enterpassword:" << endl;
cin >>password;
// username ischecked
pos =find(users.begin(),users.end(),username);
if (pos!= users.end()) {
// user informationis loading
LoadPasswords();
//password is checked
if (passwords[username] ==password) {
cout << "Youare logged in" << endl;
logged = true;
}
else {
cout << "Thepassword is incorrect" <<endl;
}
}
else {
cout << "Theusername is incorrect" <<endl;
}
}
}
intmain() {
Login();
return 0;
}
Comments
Leave a comment