1

我没有用过fstream很多,所以我有点失落。我创建了一个文本文件,其中包含我想用作程序的用户名和密码列表的随机单词列表。

我希望我的程序检查用户是否存在(行中的第一个字符串),然后检查它之后的第二个单词是否“匹配”。

到目前为止,我有这个:

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

我的文本文件包含:

香蕉苹果/n
胡萝卜草莓/n
巧克力蛋糕/n
芝士派/n

我得到我的代码现在不好,但我真的不知道我在做什么。

4

1 回答 1

1

参见下文:

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

使用while (inFile >> user >> pass){而不是while (!inFile.eof()){. 为什么?

试试这个:

#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;
        }
    }
}
于 2019-02-19T02:51:23.500 回答