我想比較兩個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;
}
使用==>爲size_t半=標準::分鐘< size_t >(newPW.length(),password.length())>> 1; 請記住,你可以有一半= 0,這樣一半 - 1 <0 –