C++逐行读取文件并检查它是否等于特定字符串

C++ Reading File by line and checking if it equals to a specific string

本文关键字:是否 于特定 字符串 检查 逐行 读取 文件 C++      更新时间:2023-10-16

我想创建一个程序,用户可以在其中输入一组特定的字符,然后检查已经创建的文件是否每行都有用户键入的完全相同的字符。

我的代码:

string line;
string employeeID;
bool found = false;
ifstream  stream1("employees.txt", ios::app);
do{
    cout << "Enter Employee Password:" << endl;
    getline(cin, employeeID);
    while (!stream1.eof())
    {
        getline(stream1, line);
        if (employeeID == line){
            found = true;
        }
    }
} while (found == false);

我的employees.txt文件包含:

ADH4172
DGGH481

换句话说,如果他们不输入ADH4172或DGHH481作为员工ID,我不希望它继续执行该程序。然而,上面的方法似乎不起作用。谢谢你的帮助

修复后的代码:

string line;
    string employeeID;
    bool found = false;
    cout << "This portion of the program asks for the employee password, and checks its existence from a text files.nThe passwords are 5555 and 6666. Any other string will not workn" << endl;
    do{
        ifstream  input("employees.txt", ios::app);
        cout << "Enter Employee Password:" << endl;
        getline(cin, employeeID);
        while (!input.eof())
        {
            getline(input, line);
            if (employeeID == line){
                found = true;
                input.close();
            }
        }
        if (found == false){
            cout << "Incorrect, try againn" << endl;
            input.close();
        }
    } while (found == false);

while (found=false)found设置为false,使条件为false,因此循环立即终止。将其更改为"find==false"。