Answer to Question #42792 in C++ for ahmed

Question #42792
Program asks user to enter user name and password If same user name exists in the primary index file, program does nothing and prints "User name already exist". Otherwise, a new record is created of type admin, and written to "users.dat" file in fixed length record structure and the primary index file is updated .
Expert's answer
#include<iostream>
#include<string>
#include<fstream>
#include<list>
#include<algorithm>

using namespacestd;

// filenames
conststring fnindex = "index.dat";
conststring fnusers = "users.dat";

// list of usernames
list<string>users;

boolAddUser (string username,string password) {
ofstream findex(fnindex,ios::app);
ofstream fusers(fnusers,ios::app);
string output;
bool res = true;

// primary index file is updated
if (findex.is_open()) {
output =username + "\n";
findex <<output;
findex.close();
} else {
res = false;
}

// new record is written"users.dat"
if (fusers.is_open()) {
output =username + "|" + "admin" + "|" +password + "\n";
fusers <<output;
fusers.close();
} else {
res = false;
}

returnres;
}

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;
}
}

intmain() {
list<string>::iteratorpos;

string username;
string password;
bool newUser = true;

LoadUsernames();

while (newUser) {
cout << "Enterusername:" << endl;
cin >>username;

cout << "Enterpassword:" << endl;
cin >>password;

//username is checked
pos =find(users.begin(),users.end(),username);
if (pos== users.end()) {
AddUser(username,password);
newUser = false;
} else {
cout << "Username already exist" << endl;
}
}

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 first!

Leave a comment

Ask Your question

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS
paypal