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

标签 c++

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

我的代码:

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 work\n" << 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 again\n" << endl;
            input.close();
        }

    } while (found == false);

最佳答案

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

关于C++逐行读取文件并检查它是否等于特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34123627/

相关文章:

c++ - CUDA 5.0 头文件

c++ - 你如何让一个函数在每次被调用时给自己加 1?

c++ - 变量在调用 lambda 之前被销毁

c++ - 使用 vector 操作的单元测试中未处理的 C++ 异常

c++ - 二叉搜索树 "remove"函数

c++ - 通过函数传递指向数组数组的指针

c++ - pjsip 新调用错误...无法找到默认音频设备 (PJMEDIA_EAUD_NODEFDEV)

c++ - Windows XP 套接字错误与 recv()

c++ - 生成形状的简单方法

c++ - 有没有办法告诉 doxygen 不要在调用图中包含函数?