【问题标题】:Character Test Function inside Ternary Operator三元运算符中的字符测试函数
【发布时间】:2021-01-25 19:29:00
【问题描述】:

我对 C 和编程非常陌生。

我遇到了以下 if 语句中使用的字符测试函数的示例编码。

> for(i=0; i<strlen(password); i++)
{
    if(isdigit(password[i]))
    {
        hasDigit = 1;
        continue;
    }
    if(isupper(password[i]))
    {
        hasUpper = 1;
        continue;
    }
    if(islower(password[i]))
    {
        hasLower = 1;
}

if ((hasDigit) && (hasUpper) && (hasLower))
    {
        printf("\n Well done, %s\n", user);
        printf("Your password is successfully created with an upper and a lowercase");
        printf(" letters and number(s).\n");
    }else
    {
        printf("\n\n You should consider a new password, %s\n", user);
        printf("One that uses upper and lowercase letters");
        printf(" and a number.\n");
    }

然后我想使用三元运算符来简化它,所以我在for循环中做了以下操作。

    hasDigit = isdigit(password[i])? 1:0;
    continue;

    hasUpper = isupper(password[i])? 1:0;
    continue;

    hasLower = islower(password[i])? 1:0;

结果不同。我想知道如何纠正它,或者在这种情况下我是否可以使用三元运算符?

【问题讨论】:

  • 问问自己,当循环找到一个数字作为第一个字符,而不是在其他位置时会发生什么。它将撤消设置的标志。你不应该把它设置为0,因为你已经找到了一个数字。
  • 第二版中你总是continue判断字符是否为数字
  • 至于三元:hasDigit = isdigit(password[i])? 1:0;hasDigit = isdigit(password[i]);的效果差不多
  • 是的,你可以,但它是毫无意义的迟钝。 hasDigit = isdigit() ? 1 : hasDigit;。但首先强迫用户使用这些字符是非常愚蠢的。您将接受Trump2020 之类的密码,是的,很难猜到。

标签: c conditional-statements conditional-operator


【解决方案1】:

原始代码对标志执行 set 操作,但从不执行任何 clear 操作。

三元实现将也明确。因此,它与原始代码的作用不同。此外,在您的代码中,continue 是无条件完成的,这也会改变最终结果(在大多数情况下)。

换句话说:您实现的功能与原始代码不同。

如果您真的想使用三元运算符,解决方法是:

hasDigit = isdigit(password[i]) ? 1 : hasDigit;
hasUpper = isupper(password[i]) ? 1 : hasUpper;
hasLower = islower(password[i]) ? 1 : hasLower;

但对我来说,代码有“味道”,我更喜欢使用 if 语句的版本。

continue 的“缺乏”还意味着您执行了一些不必要的函数调用,这可能会对性能产生一些影响,但这可能是一个小问题。

【讨论】:

    【解决方案2】:

    你需要三元运算符吗?

    for (i = 0; i < strlen(password); i++)
    {
        int c = password[i];
        hasDigit |= isdigit(c);
        hasUpper |= isupper(c);
        hasLower |= islower(c);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      • 2019-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-24
      相关资源
      最近更新 更多