2016-01-16 87 views
1

我想比較兩個C++字符串。該函數傳遞一箇舊密碼與一個新密碼進行比較。新密碼的條件是新密碼和舊密碼的前半部分不能相同,新密碼和舊密碼的後半部分不能相同。例如,如果舊密碼爲ABCDEFGH且新密碼爲ABCDyzyz,則由於這些密碼的前半部分相同,因此不會接受新密碼。到目前爲止我已經提出了這個問題,它運行,但顯示不顯示輸出語句。我是否正確比較它們?在C++中比較兩個密碼進行驗證

bool changePassword(string& password) 
{ 
string newPW; 
int lengthnewPW; 
int lengtholdPW; 
float sizeN; 
float half; 

do 
{ 
    cout << "Enter new password: "; 
    getline(cin, newPW); 



    lengthnewPW = newPW.length(); 
    lengtholdPW = password.length(); 
    if (lengthnewPW < lengtholdPW) 
    { 
     sizeN = lengthnewPW; 
    } 
    else if (lengtholdPW < lengthnewPW) 
    { 
     sizeN = lengtholdPW; 
    } 
    else 
     sizeN = lengtholdPW; 


    half = sizeN/2; 


    if (newPW.compare(0, half - 1, password) == 0 || newPW.compare(half, (sizeN - half) - 1, password) == 0) 
    { 
     cout << "The new password cannot start or end with " << half << " or more characters that are the same as the old password" << endl << endl; 
    } 


} while (newPW.compare(0, half - 1, password) == 0 || newPW.compare(half, (sizeN - half) - 1, password) == 0); 

return true; 
} 
+0

使用==>爲size_t半=標準::分鐘< size_t >(newPW.length(),password.length())>> 1; 請記住,你可以有一半= 0,這樣一半 - 1 <0 –

回答

0

嘗試:

bool changePassword(const string& password) 
{ 
    for(; ;) 
    { 
     string newPW; 
     cout << "Enter new password: "; 
     getline(cin, newPW); 

     size_t half = (newPW.length() < password.length() ? newPW.length() : password.length()) >> 1; 
     // May want to to add: if(!newPW.empty()) 
     if((password.size() <= 2) || 
      ((password.substr(0, half) != newPW.substr(0, half)) && 
       (password.substr(password.size() - half) != newPW.substr(newPW.size() - half)))) 
      return true; // <-- Will you ever return non-true? Max retries? 

     cout << "The new password cannot start or end with " << half << " or more characters that are the same as the old password" << endl << endl; 
    } 
    return true; 
} 
+0

這不是檢查密碼的後半部分。此外,它會拒絕所有1-2個字符的原始密碼,即使OP從未提及任何有關該密碼的內容。 – bcrist

+0

@bcrist你說得對。糾正。 –

+0

'x >> 1'用於將'x'減半。不要這樣做。這不是90年代了。 – bolov