function - Comparing two passwords for validation in C++ -
i trying compare 2 c++ strings. function passes old password compared new password. condition new password first half of new password , old password cannot same , second half of new password , old password cannot same. example, if old password abcdefgh , new password abcdyzyz, new password not accepted since first half of these passwords same. have come far , runs display doesn't show output statement. comparing them correctly?
bool changepassword(string& password) { string newpw; int lengthnewpw; int lengtholdpw; float sizen; float half; { 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 " << half << " or more characters same old password" << endl << endl; } } while (newpw.compare(0, half - 1, password) == 0 || newpw.compare(half, (sizen - half) - 1, password) == 0 ); return true; }
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 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; // <-- ever return non-true? max retries? cout << "the new password cannot start or end " << half << " or more characters same old password" << endl << endl; } return true; }
Comments
Post a Comment