简体   繁体   中英

Reading multiple lines from textfile in c++

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM