【问题标题】:Checking for a lowercase character or space in a string. Boolean not working检查字符串中的小写字符或空格。布尔值不起作用
【发布时间】:2019-09-11 07:26:18
【问题描述】:

这应该检查输入的字符串是否是有效的许可证号。有效数字不能包含任何小写字母或空格。如果我输入“cat”,它应该看到字符“c”较低,因此应该将 bool isValid 设置为 false,从循环中中断,然后打印“cat is not a valid license number”。然而它没有,它只是使 bool isValid 成为我一开始设置的任何东西,这是真的。因此,如果我将其初始化为 false 并输入“CAT”,isValid 仍然是 false。

int main()
{
    // Input
    cout << "Enter a valid license number: ";
    string license_number;
    getline(cin, license_number);
    cout << endl;

    // Initialize boolean
    bool isValid = true;

    // Loop to check for space or lowercase
    for (int i = 0; i < license_number.size(); i++)
    {
        if (isspace(license_number[i]) || islower(license_number[i]))
        {
            bool isValid = false;
            break;
        }

        else
            bool isValid = true;
    }

    // Output
    if (isValid == true)
        cout << license_number << " is a valid license number." << endl;

    else
        cout << license_number << " is not a valid license number." << endl;

    return 0;
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    问题出在这里:

    bool isValid = false;
        break;
    

    您没有更改您的 isValid 变量。相反,您正在创建一个新的isValid,它隐藏了原始isValid,并且该新变量在之后立即超出范围时被丢弃。因此,您原来的 isValid 不受影响。删除此行中的bool 即可。


    除此之外你还可以删除这部分

    else
        bool isValid = true;
    

    因为当到达这部分代码时,isValid 无论如何都是true。您也可以简单地写if (isValid),而不是if (isValid == true)。你甚至可以像这样简化代码:

    // Loop to check for space or lowercase
    for (int i = 0; i < license_number.size(); i++)
    {
        if (isspace(license_number[i]) || islower(license_number[i]) )
        {
            cout << license_number << " is not a valid license number." << endl;
            return 0;
        }
    }
    
    cout << license_number << " is a valid license number." << endl;
    
    return 0;
    

    另外,如果你有时间,看看Why is "using namespace std;" considered bad practice?

    【讨论】:

    • 非常感谢
    【解决方案2】:

    您只需要从 for 循环中删除 bool 类型(在 ifelse 条件中) - 它定义了一个新的局部变量 isValid,它隐藏了循环外的 isValid 定义(在评论// Initialize boolean 下)& 一旦命令流离开它被定义的块,这个本地定义就不再存在了。

    在该块之外,定义 isValid = true 再次发挥作用(处理逻辑保持不变)。

    【讨论】:

      猜你喜欢
      • 2014-10-11
      • 2013-08-22
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 2022-10-26
      相关资源
      最近更新 更多