2013-07-26 53 views
-1

我試圖使這個密碼驗證程序,並在即時獲取無限循環。它非常令人沮喪。我一直在這個工作大約一天半... 該計劃的目的是確保通過至少6個字符長,並有一個上,一個下,一個數字以及。輸入密碼時出現無限循環

#include <iostream> 
#include <cstring> 
#include <cctype> 
using namespace std; 


bool testPass(char []); 
int main() 
{ 
    char *password; 
    int length; 
    int num; 

    cout << "Please enter how many characters you would like your\npassword to be."; 
    cout << " Your password must be at least 6 characters long." << endl; 
    cin >> num; 


    while(num < 6) 
    { 
     cout << "Please enter a password length of at least 6 characters." << endl; 
     cin >> num; 
    } 


    password = new char[num+1]; 


    cout << "Please enter a password that contains at least one uppercase letter, "; 
    cout << "one\nlowercase letter, and at least one digit." << endl; 


    cin >> password; 


    length = strlen(password); 



    while (length != num) 
    { 
     cout << "Your password is not the size you requested. "; 
     cout << "Please re-enter your password." << endl; 
     cin >> password; 
     length = strlen(password); 
    } 

    if (testPass(password)) 
     cout << "Your password is valid." << endl; 
    else 
    { 
     cout << "Your password is not valid. "; 
     cout << "Please refer to the above warning message." << endl; 
    } 

    delete[] password; 

    system("pause"); 
    return 0; 
} 



bool testPass(char pass[]) 
{ 
    bool aUpper = false, 
     aLower = false, 
     aDigit = false ; 
    for (int i = 0 ; pass[i] ; ++i) 
     if (isupper(pass[i])) 
      aUpper = true ; 
     else if (islower(pass[i])) 
      aLower = true ; 
     else if (isdigit(pass[i])) 
      aDigit = true ; 
    if (aUpper && aLower && aDigit) 
     return true; 
    else 
     return false ; 
} 
+1

顯然你需要指定一個大於5的數字。附加一個調試器,它有很大幫助! –

+0

您是否在第一次提示時輸入密碼? 您需要輸入一個數字> 6第一個 – P0W

+0

我認爲這是您不當使用「num」。你應該嘗試創建一個字符串,並使用'cin >> string'來處理'while(string.length()<6)'; –

回答

0
int num; 
cin >> num; 

上面的代碼會問了許多並將其存儲在NUM。這不是您想要的,您需要將密碼存儲在字符串中,並根據需要檢查長度和其他屬性。

cin >> str; 

只要發現任何空格字符就停止讀取,這不是我們想要的。

請看看http://www.cplusplus.com/doc/tutorial/basic_io/

的解決方案可能是下面的代碼:

string password; 
bool valid = false; 

while (!valid) { 
    getline(cin, password); 
    valid = password_valid(password); 
    if (!valid) { 
     // display error message 
    } 
} 

// password is valid 
0

如果你想至少6個字符,你需要<=所以你while循環應該是 while(num <= 6)