c++ ifstream只读取最后一行



我正在编写一个允许用户注册帐户的程序。当用户注册一个帐户时,用户名和密码将输出到一个文本文件"database.txt"

如果用户忘记密码,还可以通过输入用户名来搜索他们的密码。我发现,当只有一个用户在.txt文件数据库中注册时,这种方法可以正常工作。但是,当有多个用户时,无论搜索哪个用户名,忘记密码函数都会返回最近注册用户的密码。

database.txt如下:

user1 111
user2 222
user3 333

无论输入哪个用户来查找密码,该函数总是返回333,这是最近注册的用户的密码。如何解决这个问题,以便无论搜索哪个用户,都会输出他们的密码?

函数如下:

void forgot()
{   
int ch;
system("cls");
cout << "Forgotten? We're here to help." << endl;
cout << "Choose one of the options below: " << endl;
cout << "1. Forgot my password" << endl;
cout << "2. Forgot my username" << endl;
cout << endl;
cout << "Enter your choice: ";
cin >> ch;
switch(ch)
{
case 1: // search for username to find password
{
int count = 0;
string searchUser, su, sp;
cout << "Enter your username: "; 
cin >> searchUser;
ifstream searchUserName("database.txt"); 
while(searchUserName >> su >> sp)
{
if(su == searchUser)
{
count = 1;
}
}
searchUserName.close();
if(count == 1)
{
cout << "Account found!" << endl;
cout << "Your password is: " << sp;
cin.get();
cin.get();
system("cls");
menu();
}
else 
{
cout << "Sorry, that user ID does not exist." << endl;
cout << "Please contact our service team for more details." << endl;
cin.get();
cin.get();
system("cls");
menu();
}
break;
}
case 2: // search for password to find username
{
int count = 0;
string searchPass, su2, sp2;
cout << "Enter your password: "; 
cin >> searchPass;
ifstream searchPassword("database.txt");
while(searchPassword >> su2 >> sp2)
{
if(sp2 == searchPass)
{
count = 1;
}
}
searchPassword.close();
if(count == 1)
{
cout << "Your password has been found." << endl;
cout << "Your username is: " << su2;
cin.get();
cin.get();
system("cls");
menu();
}
else
{
cout << "Sorry, we couldn't find your password in our database." << endl;
cout << "Please contact our team for more information." << endl; 
cin.get();
cin.get();
system("cls");
menu();
}
break;
}
default: 
cout << "Invalid choice, please try again." << endl;
system("cls");
forgot();
}
}

一旦在这里找到用户名,就应该跳出while循环:

while(searchUserName >> su >> sp)
{
if(su == searchUser)
{
count = 1;
break; // add this
}
}

现在它将继续覆盖以前找到的用户名,直到searchUserName >> su >> sp不再是true,这是一旦它遇到EOF在大多数情况下。

程序的另一部分也有同样的问题。

我个人会重写代码,使是否找到匹配的密码成为循环条件的一部分。

最新更新