Homework Password System

Well I gave in my assignment for my CSCI Lab class I received feedback from the teacher :[b]This program only works if the user's password begins with the string "password", which will not always be the case.[/b] I do not understand what he means by this.

This is the code
# include <iostream>
# include <fstream>
# include <string>
using namespace std;
int main ()
{
//Variables
string user_id; //user from file
string password; //password from file
size_t pos;
string user, user_password; //inputs from the user

//User Interaction
cout << "What is your Username?" <<endl;
cin >> user; //user enter username

cout << "Enter your Password?" <<endl;
cin >> user_password; //user enter password


//File Input
string line; //Opening the filed needed to check User ID and password
ifstream a1("lab1.data");
getline(a1,line);
a1.close();


//Breaking String into Two
user_id=line.substr (0,17); //Takes only the user ID from the file
pos = line.find("password");
password = line.substr(pos); //Only the password is taken


//New Values to compare
string File = user_id + password; //adds the info of the file together
string Person = user + user_password; //adds the info of the user inputs together

//Successfull Log IN or Wrong Information
if (File == Person) {
cout << "LOGGED IN" << endl;
}

else {
cout << "WRONG" << endl;
}
return 0;
}
Well I guess your Teacher is saying that because of the following line in your code :

pos = line.find("password")

If that is the case, your Teacher is almost correct but not entirely. Tell your teacher that your password file has the actual passwords prefixed by the string "password".
Last edited on
the password from the data file is: password
If you are looking for a hard-coded password such as "password"
pos = line.find("password")

then its true that you could never use another password without changing your code. To be more flexible, your code should not know the password before reading the file. It is the file that tells you what the true password is, thus allowing the user to use any password they please (without editing the code).
Last edited on
Your password entered into the program has to be prefixed with "password", but you knew that. Here's why:
1
2
pos = line.find("password");
password = line.substr(pos);

Your find function will return the position of the first character of "password". std::string::substr(size_t) will take everything after and including a specified character. So if you had a password in the file of "wipqozn", then you'd have to enter into your program "passwordwipqozn" for there to be a match. To fix this, simply add the number of characters in "password" to pos, and then redefine what your password is after the word password.

Or come up with a different format storing your password.

-Albatross
Topic archived. No new replies allowed.