Reputation: 13
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.
Upvotes: 1
Views: 1795
Reputation: 368
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;
}
}
}
Upvotes: 1