[英]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<<"\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;
您還需要有一個標志。 如果記錄不在第一個位置,則可能顯示“登錄失敗”,但記錄可能存在於第二個位置。 因此,請保留標志變量。 如果遍歷整個文件后標記變量尚未更新,則打印“登錄失敗”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.