通过文本文件登录/注册帐户
C++ fstream - Account login/registration via txt file
我是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)
{
}
相关文章:
- 无法将结构注册为增强几何体3D点
- 如何使用AngelScript注册SFML Vector2运算符
- 在遍历处理程序的向量时注册和注销处理程序
- 有没有任务栏API可以立即应用注册表更改
- 使用QJsEngine在Qt中注册自定义类型
- 检查注册表项是否链接到(或副本)另一个注册表项
- 密码登录程序将永远循环并显示不正确的结果
- 如何使用 TStyleManager::UnRegisterStyle() 取消注册样式
- WINAPI 注册应用程序重新启动时不清除打开的套接字
- SFML 碰撞永远不会在我的系统中注册
- 尝试从C++访问 UWP 的电子邮件邮件类会导致"REGDB_E_CLASSNOTREG类未注册"错误
- 如何检查cURL是否成功登录?c ++
- 用于创建/注册虚拟存储设备的 IOKit 驱动程序
- 如何添加预防措施以绕过未注册Microsoft.ACE.OLEDB.12.0?
- 进程外 EXE 的免注册 COM
- 如何注册Qt C++对象以在QML中使用它
- 在Qt中注册自定义元类型的别名类型
- 禁用地址共享注册表不起作用
- C 注册并登录程序帮助
- 通过文本文件登录/注册帐户