gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:22:14 30 4
gpt4 key购买 nike

我正在尝试比较两个 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;
}

关于c++ - 比较两个密码以在 C++ 中进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34824488/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com