我正在编写一个简单的程序,用于验证最少两个数字的8个字符的密码。这似乎通常分配给初学者,但我无法在网上任何地方找到任何问题的答案,但未能完成任务,但我仍然想学习如何做到这一点,并认为这对我这样的其他初学者有帮助< / p>
我需要验证包含字母和数字的字符串是否包含至少两个数字。
isalpha()或isdigit()一次只读取一个字符,并且strspn(,)或strcspn()在到达另一个段中找不到的字节时停止计算长度,所以如果输入密码就像&#34; A1B2C3&#34;使用其中一个函数,输出将为1或0。 我也尝试将数据类型从char切换到int,反之亦然。
这是我到目前为止所做的:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <ncurses.h>
int main() {
char password[8];
char numVerify[] = "1, 2, 4, 5, 6, 7, 8, 9";
int valid = 10
do {
printf("Enter Password: \n");
scanf("%s",password);
int a = strspn(password,numVerify);
if (strlen(password) <= 8 && a >= 2 ) {
printf("You have entered a valid password");
break;
}
else {
printf("\e[2J\e[H");
printf("Invalid Password!\nEnter password with a maximum of 8 characters and at least 2 numbers\n");
}
}while(valid > 5 );
return 0;
}
答案 0 :(得分:0)
您需要计算字符串中的数字数。使用for循环遍历字符串
中的每个字母int numcount=0;
for (i = 0; i < strlen(string); i++) {
if(isdigit()) numcount+=;}
if(numcount>=2) //password is good {}
else {} //bad
可能不是很好的语法。有一段时间没有使用过C,但这是个主意。