【问题标题】:How to keep looping until password meets condition in C++?如何保持循环直到密码满足 C++ 中的条件?
【发布时间】:2016-01-16 22:28:17
【问题描述】:

我正在尝试继续循环以要求用户输入新密码,直到满足条件。将此新密码与传递给此函数的旧密码进行比较。条件是新旧密码的前半部分不能相同,新旧密码的后半部分不能相同。如果满足此条件,则将旧密码更改为新密码。到目前为止我有这个,但它只工作一次,并且在满足条件之前它不会一直循环询问新密码。有没有办法让它一直循环,直到新密码通过条件?

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;

 }

【问题讨论】:

  • 如果前半部分一样,后半部分一样,那不就意味着整个东西都是一样的吗?
  • &amp;&amp; 更改为||!(A and B) &lt;=&gt; !A or !B

标签: c++ function loops pass-by-reference do-while


【解决方案1】:

您的 while 条件与密码为真的条件相同。您必须在密码为 not true 时进行设置。添加 !到while条件。

【讨论】:

  • 谢谢!它可以工作,但由于某种原因旧密码不会更改为新密码。当我尝试在主函数中显示密码时,旧密码仍然出现。 oldpassword = newPW;不会把旧密码覆盖成新密码吗?
  • nop,因为如果您想用新密码替换旧密码,则返回 true...您必须在“return true”行之前添加此行,在while条件之后。
  • 所以现在有两个oldpassword = newPW;?那么oldpassword = newPW; 在每条返回真线之前?
  • 我认为第二个“oldpassword = newPW;”由于循环条件,从未使用过。
  • 所以我应该删除第二个“oldpassword = newPW”,并保持循环条件之后的第二个返回true?
猜你喜欢
  • 2018-06-29
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-02
  • 2016-04-12
  • 1970-01-01
  • 2022-11-23
相关资源
最近更新 更多