使用二进制文件的用户名和登录系统

username and login system using binary files

本文关键字:登录 系统 用户 二进制文件      更新时间:2023-10-16

>用户名和密码系统,使用登录功能存储帐户信息并使用功能登录登录。由于某种原因,程序在登录时读取二进制文件,但无法识别给定的名字,姓氏和密码是否与文件中的任何数据匹配。

int userno = 0;
bool check;
char firstname[10],lastname[10],password[10];

class user
{
public:
int uid;
char fname[20],lname[20],pword[20];
int age;
}u[100];
getuserno()
{
fstream f("user.dat",ios::in);

for(int i=0 ; !f.eof() ; i++)
{
f.read((char*)&u[i],sizeof(u[i]));
userno = i;
}

}

'

int signin()
{   
ofstream entry("user.dat",ios::out|ios::app|ios::binary);
if(!entry) {
cout << "Cannot open file!" << endl;
return 1;
}
cout<<"Enter first namen";
cin>>u[userno].fname;
cout<<"Enter last namen";
cin>>u[userno].lname;
cout<<"Enter your passwordn";
cin>>u[userno].pword;
cout<<"Enter your agen";
cin>>u[userno].age;
if(u[userno].age<18)
{
cout<<"You must be 18 or older"<<endl;
cin>>u[userno].age;
}
u[userno].uid = userno;
entry.write((char*)&u[userno],sizeof(u[userno]));
if(!entry.good()) {
cout << "Error occurred at writing time!" << endl;
system("pause");
}
userno++;
entry.close();
system("cls");
}

'

int login()
{   
x:check=false;
ifstream login("user.dat",ios::in|ios::binary);
if(!login) {
cout << "Cannot open file!" << endl;
return 1;
}
cout<<"Enter your first namen";
cin>>firstname;
cout<<"Enter your last name:"<<endl;
cin>>lastname;
cout<<"Enter passwordn";
cin>>password;
login.seekg(0);
for(int i = 0; i < userno ;i++)
{   
login.read((char*)&u[i],sizeof(u[i]));
if(firstname == u[i].fname && lastname == u[i].lname && 
password == u[i].pword)
{
check=true; 
cout<<"IT WORKS!!!!";
}
cout<<check;
}
if(check == false)
{
cout<<"Incorrect username or password!!!!n";
goto x;
system("cls");
}
login.close();
system("cls");
}

for 循环读取文件中的每个记录,但即使输入了正确的信息,仍会将检查输出为 false(0(。

您的问题缺少最小完整和可验证的示例(又名 mcve(,因此不可能说您的代码是否有更多问题,尽管一个问题是:

for(int i = 0; i < userno ;i++)
{   
login.read((char*)&u[i],sizeof(u[i]));
if(firstname == u[i].fname && lastname == u[i].lname && 
password == u[i].pword)
{
check=true; 
cout<<"IT WORKS!!!!";
}
cout<<check;
}

循环遍历u元素,并在每次迭代中检查名称和密码是否匹配。循环后,check只会告诉您最后一个条目是否匹配,但如果匹配是之前的,check将在下一次迭代时被false覆盖。

找到匹配项后,您需要打破循环:

for(int i = 0; i < userno ;i++)
{   
login.read((char*)&u[i],sizeof(u[i]));
if(firstname == u[i].fname && lastname == u[i].lname && 
password == u[i].pword)
{
check=true;             
cout<<"IT WORKS!!!!";
break;                 // exit the while loop 
}
}
cout<<check;                   // move the print out of the loop

此外:

  • 您可以使用更清晰的while循环时,不要使用goto
  • 阅读为什么使用命名空间 std 被认为是不好的做法
  • 除非以后需要它,否则无需将文件中的所有条目存储在数组中。在循环中,您只需要一个条目。