我想创建一个程序,用户可以在其中输入一组特定数量的字符,然后检查已创建的文件是否具有用户在每一行中键入的完全相同的字符。
我的代码:
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/