如何检查 c++ 中是否存在记录(数据文件处理)
How to check if a record exist in c++(data file handling)?
我正在尝试检查用户是否具有有效的帐号和密码(两者都是整数类型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;
你也需要有一个标志。如果第一个位置没有记录,则可能会显示"登录失败",但记录可能存在于第二个位置。所以保留一个标志变量。如果遍历整个文件后标志变量尚未更新,则打印"登录失败"。
相关文章:
- C++模板来检查友元函数的存在
- 既然存在危险,为什么项目要使用-I include开关
- 我们可以访问一个不存在的联盟的成员吗
- C++:对不存在的命名空间使用命名空间指令
- 将两个数组中的差异记录在第三个数组中
- C++quit()函数中可能存在作用域问题
- C++擦除(如果存在)
- g++ 说函数不存在,即使包含正确的标头
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 有了gcc,是否可以链接库,但前提是它存在
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- gcc和clang在表达式是否为常量求值的问题上存在分歧
- C++Builder中的OnClick事件签名存在问题
- 如何正确地将分支添加到已存在的树中
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 如何检查QList中是否存在值
- 根据某个函数是否存在启用模板
- 如何将分支添加到已存在的TTree:ROOT
- 在不存在的记录上调用 remove 会使程序崩溃
- 如何检查 c++ 中是否存在记录(数据文件处理)