Answer to Question #42790 in C++ for ahmed

Question #42790
how to do a login function using primary index and the primary index is the username?
1
Expert's answer
2014-05-28T09:54:02-0400
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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS