I am trying to make a login programme that reads and writes from a textfile. For some reason, only the first line of the textfile works but the rest wont be successful login.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool loggedIn() {
string username, password, un, pw;
cout << "Enter username >> "; cin >> username;
cout << "Enter password >> "; cin >> password;
ifstream read("users.txt");
while (read) {
getline(read, un, ' ');
getline(read, pw);
if (un == username && pw == password) {
return true;
}
else {
return false;
}
}
}
Text File:
user1 pass1
user2 pass2
Alternatives I tried:
read.getline(un, 256, ' ');
read.getline(pw, 256);
CodePudding user response:
while (read)
is the same as while (!read.fail())
, which is the wrong loop condition to use in your situation. You are not checking if both getline()
calls are successful before comparing the strings they output.
You also need to move the return false;
statement out of the loop. Since you have a return
in both the if
and else
blocks, you are comparing only the 1st user in the file and then stopping the loop regardless of the result. You want to keep reading users from the file until a match is found or the EOF is reached.
Try this instead:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool loggedIn() {
string username, password, un, pw;
cout << "Enter username >> "; cin >> username;
cout << "Enter password >> "; cin >> password;
ifstream read("users.txt");
while (getline(read, un, ' ') && getline(read, pw)) {
if ((un == username) && (pw == password)) {
return true;
}
}
return false;
}
Alternatively, use 1 call to std::getline()
to read an entire line, and then use std::istringstream
to read values from the line, eg:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
bool loggedIn() {
string username, password, un, pw, line;
cout << "Enter username >> "; cin >> username;
cout << "Enter password >> "; cin >> password;
ifstream read("users.txt");
while (getline(read, line)) {
istringstream iss(line);
if ((iss >> un >> pw) && (un == username) && (pw == password)) {
return true;
}
}
return false;
}