Mark
Mark

Reputation: 283

Comparing two passwords for validation in C++

I am trying to compare two C++ strings. This function passes an old password to be compared with to a new password. The condition for this new password is that the first half of the new password and old password cannot be the same and the second half of the new password and old password cannot be the same. For example, if the old password was ABCDEFGH and the new password was ABCDyzyz, the new password will not be accepted since the first half of these passwords are the same. I have come up with this so far and it runs but the display doesn't show the output statement. Am I comparing them correctly?

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

Upvotes: 1

Views: 440

Answers (1)

George Houpis
George Houpis

Reputation: 1729

Try:

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

Upvotes: 0

Related Questions