2012-05-12 38 views
3

我有一個包含用戶名和密碼的auth.txt文件。我的目標是在進入下一個菜單之前使用此文件查看用戶是否輸入了有效的用戶名和密碼。 例如。 auth.txt包含用戶通過。當他們選擇一個菜單時,它會要求他們登錄。如果他們輸入不正確,它什麼也不做。每個密碼和usrname存儲在auth.txt文件中。 我嘗試使用下面的代碼,但什麼都沒有。請提前幫助和感謝。使用C++中的文本文件進行身份驗證

if(getline(inauth, line)){ 

    if(line==user&& line==password){ 
    //your in 

    }else cout<<"bye"; 
    } 
+2

行是用戶名和密碼在同時?這就是你的代碼所暗示的。 – John3136

+0

你真的不想存儲用戶的密碼。存儲密碼的散列,當它們輸入新密碼時,以相同方式對其進行散列,以查看是否獲得相同結果。你需要一個加密散列(例如SHA-256)。 –

回答

0

你只是讀一個行,然後你想比較這兩個「用戶」和「密碼」。這當然是行不通的。你需要兩次調用getline。不要忘記檢查錯誤,使用用戶身份驗證永遠不會太安全。嘗試是這樣的:

ifstream inauth("Secret password herein.txt"); 

if (inauth) { 
    string usr, psw; 

    if (getline(inauth, usr) && getline(inauth, psw) { 
     if (usr == user && psw == password) { 
      cout << "Phew, everything's fine."; 
     } else { 
      cout << "Wrong password/username."; 
     } 
    } else { 
     cout << "I guess somebody opened the file in notepad and messed it up." 
    } 
} else { 
    cout << "Can't open file, sorry."; 
} 
1

我不是一個VC++開發人員,但是這應該是您想要完成的正確邏輯。

// keep looping while we read lines 
while (getline(inauth, line)) 
{ 
    // valid user 
    if (line == user) 
    { 
     // read the next line 
     if (getline(inauth, line2)) 
     { 
      if (line2 == password) 
      { 
       // successfully authenticated 
       cout << "Success!"; 
      } 
      else 
      { 
       // valid user, invalid password 
       // break out of the while loop 
       break; 
      } 
     } 
    } 
} 
0

如果你的用戶名和密碼存儲在由分隔同一行,說一個空格,然後,你就必須做

#include <sstream> 

string line, username, password; 
istringstream instream; 
while (getline(inauth, line)) 
{ 
    // extract username and password from line using stringstream 
    instream.clear(); 
    instream.str(line); 
    instream >> username >> password; 
    // do something here 
} 
相關問題