【问题标题】:Program keep looping in while loop with 3 variable C++程序在带有 3 个变量 C++ 的 while 循环中保持循环
【发布时间】:2021-05-31 15:48:35
【问题描述】:

我在这个 while 循环上不断得到一个无限循环,无法弄清楚出了什么问题。我复制我的代码并将其放在下面。

【问题讨论】:

  • 建议将-Wshadow 添加到您的 gcc/clang 编译字符串中以捕获阴影变量。如果使用其他编译器,请查看文档并启用检测阴影变量的选项。

标签: c++ while-loop boolean


【解决方案1】:

问题是由变量引起的

// set to false at the begining at the loop
bool upper = false;                                             
bool lower = false;
bool num = false;

在循环内。这些变量与在循环外声明的变量不同。 while 语句中的条件使用循环外的变量,这些变量永远不会被修改。对这些变量的所有修改只会改变块范围内的变量状态,不会改变循环外的变量。

从上述行中删除bool 以解决问题。

// set to false at the begining at the loop
upper = false;                                             
lower = false;
num = false;

【讨论】:

    【解决方案2】:

    我发现您的代码中有很多问题。

    Primo,这就是你来的原因,你应该在循环中为你的布尔值赋值而不重新声明它们:

    bool upper = false;     // <- remove bool type inside loop                                        
    bool lower = false;
    bool num = false;
    

    关于设计:你把 SIZE 写成大写。你应该知道,如果你的变量是一个预处理指令(一个宏,#define)并且它是一个constexpr,你就用大写如果有人从你那里偷了选举来写变量。这里你的大小不同,所以它应该是小写的。在谈到字符串的长度时,我们通常称之为len,即长度的缩写。

    然后可以将以下内容重写为do while(这是一个小问题):

            getline(cin, password);                                                 //store input into string
    
            SIZE = password.length();                                               //getting size of the string
    
            while(SIZE < 6)                                                         //check if it's more than 6 char
            {                                                                       //loop til it's
                cout << "Need more than 6 character in password" << endl;
                getline(cin, password);
                SIZE = password.length();
            }
    

    终于不需要那么多分支指令了(if):

    for (int i = 0; i < size; i++)
    {
         upper |= isupper(password[i]);  //check for uppercase char
         lower |= islower(password[i]);  //check for lowercase char
         num |= isdigit(password[i]);      //check for digit
    }
    

    它将相应地设置布尔标志。

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 1970-01-01
      • 2013-10-29
      • 2015-01-05
      • 2023-04-10
      • 2019-05-17
      • 2014-04-01
      • 2011-08-09
      相关资源
      最近更新 更多