Mark
Mark

Reputation: 283

How to keep looping until password meets condition in C++?

I am trying to continue to loop to ask a user to enter a new password until a condition is met. This new password is compared to an old password that is passed into this function. The condition is, the first half of the new and old password can't be the same AND the second half of the new and old password can't be the same. If this condition is met, the old password gets changed into the new password. I have this so far, but it only works once and it doesn't keep looping to ask for a new password until the condition is met. Is there a way to make this keep looping until the new password passes the condition?

bool changePasswordintonewPW(string& oldpassword)
{
string newPW;
int sizeN;
int half;
int lengtholdPW;
int lengthnewPW;


do
{
    cout << "Enter a new password that must meet condition: ";
    getline(cin, newPW);


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

    half = sizeN / 2;

    if( ( oldpassword.size() <= 2 ) ||
        ( ( oldpassword.substr( 0, half ) != newPW.substr( 0, half ) ) &&
          ( oldpassword.substr( oldpassword.size() - half ) != newPW.substr( newPW.size() - half ) ) ) )
        return true;

          {
            cout << "The new password cannot start or end with " << half
                 << " or more characters that are the same as the old password" << endl << endl;

          }


} while (( oldpassword.size() <= 2 ) ||
        ( ( oldpassword.substr( 0, half ) != newPW.substr( 0, half ) ) &&
          ( oldpassword.substr( oldpassword.size() - half ) != newPW.substr( newPW.size() - half ) ) ) );


    oldpassword = newPW;
    return true;

 }

Upvotes: 0

Views: 172

Answers (1)

aab
aab

Reputation: 26

Your while condition is the same condition for the password to be true. you have to set it while the password is not true. Add ! to the while condition.

Upvotes: 1

Related Questions