通过文本文件登录/注册帐户

C++ fstream - Account login/registration via txt file

本文关键字:注册 登录 文本 文件      更新时间:2023-10-16

我是c++的新手,并试图创建一个帐户管理器来处理:日志、注册、更改通行证等

我在比较用户输入的用户名和密码时遇到困难:

编辑:我的问题是getline(openFile, tempUser, ';');不转到分号后的下一行。

如果我有USERNAME;PASSWORD,它会检查用户名和密码,就像它们是帐户名一样。

这是我的LOGIN函数:

void AccountManager::login(AccountManager &account){
  string username, password, tempUser, tempPass;
  int wrongUser(0);
  fstream openFile("UserPass.txt", ios::out | ios::in | ios::app);
  if(openFile.good()){
    do{
      cout << "Type in your username: " << endl;
      getline(cin, username);
      cin.sync();
      cout << "Type in your password: " << endl;
      getline(cin, password);
      cin.sync();
      while(!openFile.eof()){
        getline(openFile, tempUser, ';');
        if(tempUser == username){
          getline(openFile.ignore(tempUser.length()+1),tempPass);
          if(tempPass == password){
            wrongUser = 1;
            cout << "Thank you for logging in. " << endl;
            switchLog(account);
          }else{
            cout << "Wrong username or password, please try again." << endl; ;
            break;
          }
        }
      };
    }while(wrongUser = 0); // <<< while loop not working
  }
  else{ //cant Open file - error handling
    if( account.UserPass[username] == password){
      switchLog(account);
    }
    else{
      cout << "The username and password do not match. ";
    }
    cerr << "Error accessing data!" <<endl;
    exit(1);
  }
  openFile.close();
}

如果检查用户名失败,则该行上仍有尚未读取的额外数据。考虑输入数据是否如下

username1;password
username2;password

当您读取第一行并且用户名不匹配时,您将在当前输入行上悬挂password 。现在你的输入是这样的

password
username2;password

下次读取用户名时,您将得到password username,其中空格是不可打印的行结尾。这将一直持续到读取整个文件,因此只能找到文件中的第一个用户名和密码对。

要解决这个问题,可以使用std::getline来跳过输入行上剩余的文本。

if(tempUser == username)
{
    // valid username. Read the password
}
else
{ 
    // skip rest of the line
    getline(openFile, tempUser);
}

或者同时读取两个值,简化逻辑

getline(openFile, tempUser, ';');
getline(openFile, tempPassword);
if(tempUser == username)
{
}