2011-04-22 78 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

沒有用戶名和密碼之間有一個空格(也沒有子彈)

相關問題