比较两个密码以在C++中进行验证

Comparing two passwords for validation in C++

本文关键字:C++ 验证 密码 两个 比较      更新时间:2023-10-16

我正在尝试比较两个C++字符串。此函数传递要与新密码进行比较的旧密码。此新密码的条件是新密码和旧密码的前半部分不能相同,新密码和旧密码的后半部分不能相同。例如,如果旧密码是 ABCDEFGH,新密码是 ABCDyzyz,则不接受新密码,因为这些密码的前半部分是相同的。到目前为止,我已经想出了这个,它正在运行,但显示没有显示输出语句。我是否正确比较它们?

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;
}

尝试:

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;
}