【问题标题】:Read Usernames and Passwords from a txt file从 txt 文件中读取用户名和密码
【发布时间】:2011-04-22 23:52:30
【问题描述】:

我需要从 .txt 文件中提取用户名和密码,但我很难思考究竟如何做到这一点。我会尝试分解它。

  1. 打开文件
  2. 读入用户名
  3. 将用户名与用户输入进行比较
  4. 将密码与与用户名关联的用户输入进行比较
  5. 如果用户名和密码匹配,则返回 true 或 false

是的,这是作业。我正在学习如何在等待 USPS 运送我的课本 txt 时使用 fstream。非常感谢您的帮助!

这是我目前所拥有的:

bool User::check(const string &uname, const string &pass)
{
    //open the file

    fstream line;
    line.open("users.txt");

    //Loop through usernames
        //If a username matches, check if the password matches
}

users.txt 文件如下所示:

ali87   8422

ricq7   bjk1903

messi   buneyinnessi

mike    ini99ou

jenny   Y00L11A09

end

【问题讨论】:

  • Mike,我想问一下你认为这个项目的“高水平”目标是什么?看起来它比仅仅理解 fstream 还要多一点……我说得对吗? (老师们真的很喜欢这样做,在每项作业中都加入“额外的学习”,他们认为自己是谁!)

标签: c++ readline fstream


【解决方案1】:

我认为以下伪算法对你来说可能是更好的选择:

  1. 输入用户名、密码
  2. 打开文件流到文件
  3. 搜索用户名匹配的流(如果未找到则退出)
  4. 如果找到,请将加密输入密码与存储的加密密码进行比较。
  5. 如果找到,则返回成功,否则,“未找到用户名或密码不正确。”。

对于第 3 步,您会将每个行缓冲区存储在一个字符串中,您可以将其存储在一个字符串容器中。 理想情况下,在此处理过程中,您可能会将字符串拆分为用户名、密码对,然后将它们存储在 std::map 中;然后通过 map.find(input username) == input password 访问它。

您不需要将地图存储超过登录过程的持续时间,然后您应该丢弃地图(可能作为本地函数变量)。

如果你的程序确实有目的,这是理想的,否则,让它工作:)。

【讨论】:

  • 我不确定,但如果这个人正在学习 fstream,我会假设他们对编程或这种语言都很陌生,但我会说我的第一件事当我读到这个问题时想到的是它很像一个哈希表。我喜欢你的回答,虽然它可能比迈克知道怎么做更先进,但这将是一个很好的做法。我投了你的票!
【解决方案2】:
【解决方案3】:

我包括iostreamfstreamcstring。并使用namespace std

int main()
{
char login_password[20];
char stored_password[20];   
char login_username[20];
char stored_username[20];

fstream pull("users.txt",ios::in);
if (!pull) { 
    cout<<"File not loaded!"<<endl;
    return -1; 
}
cout<<"Username: ";
cin>>login_username;
while(strcmp(login_username,stored_username)){ 

//if login and stored usernames are equal, function strcmp returns 0,
//at first loop they are certainly not, so it is: while(1)

    pull>>stored_username;
    if(pull.eof()){   //if it is the end of file
        cout<<"Username does not exist. "<<endl;
        return -1;  
    }
}
pull>>stored_password; 

//since username and password are in the same line, password next to
//correctly inputted username is saved in stored_password

cout<<"Password: ";   
//now user enters password to confirm username
cin>>login_password;
while(strcmp(stored_password,login_password)){
    cout<<"Wrong password. "<<endl;
    cout<<"Try again: ";
    cin>>login_password;
}
cout<<"Login successful."<<endl;
return 0;
}

users.txt 看起来像这样:

  • Lena84 uzumymw
  • Doris20 kjkszpj

用户名和密码之间有一个空格。(也没有项目符号)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    相关资源
    最近更新 更多