2017-06-27 33 views
-5

我正在寫一個程序(主要是教育目的,但如果我喜歡它,那麼我可能會在稍後使用它在更大的項目中)進行用戶名和密碼驗證。到目前爲止,我的工作「有效」,這意味着沒有錯誤,但它確實有點奇怪。它在退出之前做了大約9次(我沒有保存確切的輸出)的STUFF(),它只是一次完成。用戶名和密碼檢查

我該如何讓它做一次STUFF()?我怎樣才能使密碼輸入不可見?我怎樣才能普遍提高安全性/語法或縮短?

#include <iostream> 
using namespace std; 

void STUFF() 
{ 
    cout << "Doing stuff..." << endl; 
} 

int CREDS; 
void AUTH() 
{ 
    cout << "Username: "; string USER; cin >> USER; 
    cout << "Password: "; string PASS; cin >> PASS; 
    if (USER == "josh" and PASS == "passwd") 
    { 
     CREDS = 0; 
    } 
    else 
    { 
     CREDS = 1; 
    }; 
} 

void RETRY() 
{ 
    cout << "Authentication failed! Try again? [Y/n]" << endl; char REPLY; cin >> REPLY; 
    if (REPLY == 'Y' or REPLY == 'y') 
    { 
     AUTH(); 
    } 
    else if (REPLY == 'N' or REPLY == 'n') 
    { 
     cout << "Exiting..." << endl; 
    } 
    else 
    { 
     RETRY(); 
    }; 
} 

int main() 
{ 
    AUTH(); 
    if (CREDS == 0) 
    { 
     STUFF(); 
     return 0; 
    } 
    else if (CREDS == 1) 
    { 
     RETRY(); 
    }; 

} 
+0

不能重現:https://ideone.com/EPnGn4 – mascoj

+0

此外,您的RETRY代碼不會按照您的預期行事。即使輸入「Y」,程序也不會退回。 – mascoj

+0

我再次測試(使其成爲獲取用戶並傳遞錯誤的重試點)。選擇不退出並選擇是,然後讓他們正確退出而不做任何事情。編輯:再次複製結果兩次然後得到用戶/第一次傳遞正確,並打印「auth失敗!再試一次?」正好9次 – Josh

回答

0

我已經放棄了最後的程序,並從頭開始寫這個。 對於任何想使用C++的人來說,它都是GNU GPLv2授權的,可以在Github的Small-Projects-Cpp找到。只需下載「Userpass.zip」,因爲它不需要克隆整個存儲庫。

#include <iostream> 
#include <string> 
#include <unistd.h> 
#include <termios.h> 

getpass()使密碼輸入顯示星號。不完全看不見,但它可能是最好的解決方案。菜單()有一個開關/外殼菜單,但它是不相關的,所以我跳過它在asnwer。你可以用你想要的任何功能替換它。

int attempts = 0; 
int main() 
{ 

    while (attempts == 3) 
    { 
     cout << "Too many attempts have been made! Exiting..." << endl; exit(0); 
    }; 
    string USER; 
    cout << "Username: "; cin >> USER; 

    if (USER == "josh") 
     { 
      if (getPASS() == "hsoj") 
     { 
     cout << "\nAccess granted!\n" << endl; 
     MENU(); 
     } 
      else 
     { 
      cout << "\nAccess denied!\n" << endl; 
     attempts = attempts + 1; 
     main(); 
     }; 
    } 
    else 
    { 
     cout << "\nAccess denied!\n" << endl; 
     attempts = attempts + 1; 
     main(); 
    }; 
    return 0; 
}