1

I haven't used fstreams 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.

Jerry Stratton
  • 2,699
  • 19
  • 25

1 Answers1

1

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;
        }
    }
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
donpsabance
  • 348
  • 3
  • 9
  • I would go a step further and suggest using `std::getline()` instead of `inFile >> user >> pass`, and then use a separate `std::istringstream` to parse out the `user` and `pass`, eg: `string line; while (getline(inFile, line)) { if (istringstream(line) >> user >> pass) { ... } }` In the first way, if any given line does not have both values, it will get `while (inFile >> ...)` out of sync, whereas the second way will not do that. Either way, you should `break` the loop if a match is found, don't keep searching the file. – Remy Lebeau Feb 19 '19 at 03:11