我正在嘗試爲我在學校做的一個項目創建一個測試程序。 我的項目的一個重要方面是擁有一個登錄系統。 在int main()
我有一個菜單,根據用戶的選擇調用login();
或createAccount();
。 login();
進一步呼叫loginToken();
以生成int authToken
,其值爲0
或1
。它調用loginAuth()
,它依次檢查authToken
的值並驗證登錄。 在int main();
當我呼籲createAccount()
它將價值或newUsername
和newPassword
寫入二進制文件accounts.bin
。然而,當我打電話login()
if
條件我檢查是否打開loginEntry
說它已關閉,即使我剛剛打開它之前的行。程序沒有從二進制文件中讀取
我會很感激一些幫助,因爲這已經困擾我好幾天。
#include<iostream>
#include<string.h>
#include<fstream>
#include <limits>
using namespace std;
class Account{
private:
char enteredUsername[20];
char enteredPassword[20];
int authToken;
char newUsername[20];
char newPassword[20];
ofstream loginDetails;
ifstream loginEntry;
public:
void login(){ // to enter username or password
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //to clear cin buffer
loginEntry.open("account.bin", ios::in|ios::binary); // to read newUsername and newPassword
if (!loginDetails.is_open()) { //to check whether file is open or not
cout<<"File not open";
}
else {
loginEntry.read(newUsername,sizeof(newUsername));
loginEntry.read(newPassword,sizeof(newPassword));
}
loginEntry.close();
cout<<"\nEnter Username: ";
cin.getline(enteredUsername, sizeof(enteredUsername));
cout<<"\nEnter Password: ";
cin.getline(enteredPassword, sizeof(enteredPassword));
loginToken();
}
void loginToken(){ // to generate login token if enteredUsername and enteredPassword match newUsername and newPassword in account.bin
if(strcmp(enteredUsername,"user")==0 && strcmp(enteredPassword,"admin")==0)
authToken=1;
else
authToken=0;
loginAuth(); // to check value of login token and allow or deny access
}
void loginAuth(){
if(authToken==1)
cout<<"Login succesfull!!";
else
cout<<"Login Failed. Returning to Menu";
getchar();
}
void createAccount(){ // to create newUsername and newPassword which are saved in account.bin
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //to clear cin buffer
cout<<"\nEnter new Username: ";
cin.getline(newUsername,sizeof(newUsername));
cout<<"\nEnter new Password: ";
cin.getline(newPassword,sizeof(newPassword));
loginDetails.open("account.bin", ios::out|ios::binary); //writing in account.bin
loginDetails.write(newUsername, sizeof(enteredUsername));
loginDetails.write(newPassword, sizeof(enteredPassword));
loginDetails.close();
cout<<"\nYour account has been created. Returning to Menu";
getchar();
}
};
int main(){
Account test;
int userChoice;
do{
system("cls");
cout<<"Welcome to xyz.com";
cout<<"\n*Press 1 to Login\n*Not a memeber? Press 2 to create an account and be awesome!!\n*If you're tired, press 3 to leave "<<endl;
cin>>userChoice;
switch(userChoice){
case 1:{
test.login();
break;
}
case 2:{
test.createAccount();
break;
}
}
}while(userChoice!=3);
cout<<"GoodBye!! :)";
return 0;
}
我投票結束這個問題作爲題外話,因爲OP是變形的問題描述和源代碼,而不是隻接受他/她原來的問題的有效答案。 –
我會接受答案,那麼我應該問這是另一個問題嗎? –