简体   繁体   中英

Checking for username and password in sequence from a text file in C++

I haven't used fstream s much, so I'm a bit lost. I created a text file that has a list of random words that I wanted to use as a list of usernames and passwords for my program.

I want my program to check if the user exists (first string in the line), then check if the second word after it "matches".

So far I have this:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream inFile;
    inFile.open("userData.txt");

    // Check for error
    if (inFile.fail()) {
        cerr << "error opening file" << endl;
        exit(1);
    }

    string user, pass;
    int Count = 0;

    // Read file till you reach the end and check for matchs
    while (!inFile.eof()) {
        inFile >> user >> pass;
        if (user == "Banana", "Apple") {
            Count++;
        }
        cout << Count << " users found!" << endl;
    }
}

My text file contains:

Banana Apple /n
Carrot Strawberry /n
Chocolate Cake /n
Cheese Pie /n

I get my code is not good right now, but I don't really know what I'm doing.

Read below:

while (!inFile.eof()) {
    inFile >> user >> pass;
    if (user == "Banana", "Apple") {
        Count++; // No point in doing so because this only happens once
    }
    cout << Count << " users found!" << endl;
}

Use while (inFile >> user >> pass){ instead of while (!inFile.eof()){ . Why?

Try this instead:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream inFile;
    inFile.open("userData.txt");

    // Check for error
    if (inFile.fail()) {
        cerr << "error opening file" << endl;
        exit(1);
    }

    string user, pass;
    int Count = 0;

    // Read file till you reach the end and check for matchs
    while (inFile >> user >> pass) {
        if (user == "Banana" && pass == "Apple") {
            cout <<"user found!" << endl;
        }
    }
}

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