【发布时间】:2021-10-20 10:03:59
【问题描述】:
我正在开发一个允许用户注册帐户的程序。当用户注册账号时,用户名和密码会输出到文本文件“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();
}
}
【问题讨论】:
标签: c++ filestream