此代码在我无法诊断的两件事上出现故障,但与 if 语句隔离:if (strlen(strA) > 8)。假设我输入字符串“1234567*aA”,程序告诉我密码太长,于是我输入字符串“12345”,然后触发else if语句:else if (strlen(strA) < 9 ).但是 while 循环 while (j<=9) 中的所有内容都被触发(程序告诉我有一个数字,一个特殊字符,一个小写字母和一个大写字母)并且 do/while 循环结束,程序提示我来确认密码。那是错误的。它应该提示我再次输入密码。
我注意到的第二个问题是,如果我输入一个字符串“1111111111111111111”,这显然太长了,程序说密码太长,但是整个 do/while 循环终止并要求我确认我的密码.它应该要求我再次输入密码。
如果我取出 if 语句:if (strlen(strA) > 8) 和 else if (strlen(strA) < 9),然后运行 while 循环:while (j<=9),程序运行可以,只要我不在字符串中输入太多字符即可。
任何人都可以诊断问题吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char strA[10];
char strB[10];
char strC[] = {'1','2','3','4','5','6','7','8','9','0'};
char strD[] = {'!','@','#','$','%','^','&','*','(',')'};
char strE[] = {'a','b','c','d','e','f','g','h','i','j','k',
'l','m','n','o','p','q','r','s','t','u','v',
'w','x','y','z'};
char strF[] = {'A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S',
'T','U','V','W','X','Y','Z'};
int i, j, k;
do {
k = 0;
j = 0;
printf("Please enter your password: ");
scanf("%s", &strA);
printf("%s\n", strA);
if(strlen(strA) > 8) {
printf("That password is too long\n");
}
else if(strlen(strA) < 9) {
while (j <= 9) {
for(i = 0; i <= 9; i++) {
if(strA[j] == strC[i]) {
printf("there is a number in this string.\n");
k++;
j = 0;
while (j <= 9) {
for(i = 0; i <= 9; i++) {
if(strA[j] == strD[i]) {
printf("there is a character in this string.\n");
k++;
j = 0;
while(j <= 9) {
for(i = 0; i <= 25; i++) {
if(strA[j] == strE[i]) {
printf("there is a lowercase letter in this string.\n");
k++;
j = 0;
while(j <= 9) {
for(i=0;i<=25;i++) {
if(strA[j] == strF[i]) {
printf("there is an uppercase letter in this string.\n");
k++;
}
}
j++;
}
}
}
j++;
}
}
}
j++;
}
}
}
j++;
}
if(k < 4) {
printf("Your password must contain at least one uppercase letter, one lowercase letter, a number, and a special character.\n");
}
}
} while(k < 4);
printf("Please confirm your password: ");
scanf("%s",&strB);
while(strcmp(strA, strB) != 0) {
printf("%s\n",strB);
printf("Your passwords do not match.\nPlease confirm your password: ");
scanf("%s",&strB);
}
putchar('\n');
printf("%s\n", strA);
printf("%s\n", strB);
return 0;
}
最佳答案
我认为以下行是造成问题的原因:
char strA[10];
char strB[10];
使用默认值初始化
memset(&strA,'\0', sizeof(strA));
memset(&strB,'\0', sizeof(strB));
关于c - 字符串问题(do/while 循环和 if 逻辑),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22516376/