2011-04-22 110 views
2

我需要从.txt文件中提取用户名和密码,并且我正在困难地考虑如何执行此操作。我会尽力打破这一点。从txt文件中读取用户名和密码

  1. 打开的用户名
  2. 文件
  3. 读取比较对用户输入
  4. 一个用户名与使用用户名
  5. 返回true或如果用户名假相关的用户输入的比较密码和密码匹配

是的,这是作业。我正在学习如何在等待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 
} 

的user.txt文件,如下所示:

ali87 8422 

ricq7 bjk1903 

messi buneyinnessi 

mike ini99ou 

jenny Y00L11A09 

end 
+0

迈克。 ,我想问你,你认为这个项目的“高层次”目标是什么?它看起来更像是理解fstream ...我是否正确? (教师真的很喜欢这样做,在每个任务中加入“额外学习”,他们认为他们是谁!) – onaclov2000 2011-04-23 03:11:49

回答

2

我认为以下伪算法可能是您更好的选择:

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

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

您应该不需要存储地图的时间超过登录过程的持续时间,那么您应该丢弃地图(可能是一个本地函数变量)。

如果你的程序实际上有一个目的,这是理想的,否则,只是让它工作:)。

+0

我不确定,但如果这个人的学习fstream,我会假设他们很漂亮新编程语言或这种语言,但我会说我读到这个问题时首先想到的是它很像一个哈希表。我喜欢你的回答,虽然它可能会更先进,然后迈克知道该​​怎么做,但这将是一个好习惯。我upvoted你! – onaclov2000 2011-04-23 03:09:04

1

我包括iostream,fstreamcstring。并使用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

没有用户名和密码之间有一个空格(也没有子弹)