【发布时间】: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