C语言 如何检查字符串中是否存在至少三位数字?



我目前正在做以下任务:

一个好的密码必须至少具有 8 个字符的最小长度,并且需要至少包含三位数字。
编写一个 C 程序来检查密码是否有效,返回 true 或 false 的密码。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main()
{
char password[100];
bool hasupper = false;
bool haslower = false;
bool hasdigit = false;
scanf("%s", password);
if(strlen(password) < 8)
{
printf("Too short");
}
for( int i = 1; i < strlen(password); i++ )
{
if(isupper(password[i]))
{
hasupper = true;
}
if(islower(password[i]))
{
haslower = true;
}
if(isdigit(password[i]))
{
hasdigit=true;
}
if(hasdigit && hasdigit && hasdigit && haslower && hasupper)
{
printf("true");
}
else
{
printf("false!");
}
}
return 0;
}

但是,我仍然困惑如何让它检查至少三位数字的存在。

如何让它检查是否存在至少三位数字?

您的代码不会像您指定的那样检查字符串是否包含 3 位数字。相反,它只是检查是否存在至少一位数。键入 3 次hasdigit条件不会以不同的方式评估它,就像写true && true && truefalse && false && false一样。

相反,您应该创建一个int来计算您找到的位数,然后检查是否count >= 3

int main(void) {
char password[100];
int digits;
// hasupper, haslower have been removed, since your original question doesn't actually specify them as necessary. Feel free to put them back if they are.
scanf("%s", password);
int len = strlen(password);
if (len < 8) {
printf("Too short.");
return; // or exit, or whatever
}
for (int i = 0; i < len; ++i) {
if (isdigit(password[i])) {
++digits;
}
}
if (digits >= 3) {
printf("Good password");
}
else {
printf("Not so good password");
}
return 0;
}

最新更新