我正在尝试在 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<<"\n\n";
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<<"\n\n 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)<<"\n\n Please enter your username (Integer only)";
cin>>u.user_id;
cout<<setw(60)<<"\n\n 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));
不会得到你想要的,它从文件中获取 char* 格式的数字,而不是 int。
应该这样做:
fin >> u.user_id;
fin >> u.password;
关于c++ - 如何检查c++中是否存在记录(数据文件处理)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22846290/