如何检查 c++ 中是否存在记录(数据文件处理)

How to check if a record exist in c++(data file handling)?

本文关键字:记录 存在 文件 处理 是否 数据 c++ 何检查 检查      更新时间:2023-10-16

我正在尝试检查用户是否具有有效的帐号和密码(两者都是整数类型C++)。数据使用结构存储在.dat文件中。这是我尝试过的:

void printIntroMenu();
void printMainMenu();
void start();
void login();
void createAccount();
char menuInput;
int i=0;
struct user{
int user_id;
int password;
}u;

int main()
{
start();
return 0;
}
void start()
{
cout<<"nn";
cout<<setw(60)<<" Please select an option from the menu below:";
printIntroMenu();
cin>>menuInput;
switch(menuInput)
{
     case 'l': login();
     break;
     case 'c': createAccount();
     break;
     case 'q': exit(0);
     break;
     default: cout<<"nn Wrong Choice!! Valid choices are l,c or q.";
     start();
}
}
void createAccount()
{
ofstream fout;
fout.open("abc.dat",ios::app|ios::binary);
cout<<setw(60)<<"nn Please enter your username (Integer only)";
cin>>u.user_id;
cout<<setw(60)<<"nn Please enter your password (Integer only)";
cin>>u.password;
fout<<u.user_id<<'n'<<u.password<<'n';
fout.close();
cout<<setw(60)<<"n Thank You!! Your Account Has Been Successfully Created.";
start();
}
void login()
{
int flag=0;
 int uid;
 int pass;
ifstream fin("abc.dat",ios::in | ios::binary);
cout<<setw(50)<<"Enter your username: ";
cin>>uid;
cout<<setw(50)<<"Enter your password: ";
cin>>pass;
while(!fin.eof())
{
    fin.read((char*)&u,sizeof(user));
    if(u.user_id==uid && u.password==pass)
    {
        flag=1;
        cout<<"n Login Successful!!";
    }
    else{
        cout<<setw(60)<<"*************** LOGIN FAILED! ***************";
    start();
    }
}
}

无论我在登录菜单中输入什么,我总是得到登录失败作为输出。请告诉我存储数据或从文件中检索数据的结构是否有任何问题,或者代码中是否缺少任何内容。

你忘记了字符串到数字的转换,因为这个

fin.read((char*)&u,sizeof(user));

不会得到你想要的,它从文件中获取字符*格式的数字,而不是整数。

应该这样做:

fin >> u.user_id;
fin >> u.password;

你也需要有一个标志。如果第一个位置没有记录,则可能会显示"登录失败",但记录可能存在于第二个位置。所以保留一个标志变量。如果遍历整个文件后标志变量尚未更新,则打印"登录失败"。