【发布时间】:2014-01-04 17:38:27
【问题描述】:
我正在编写一个程序,允许用户输入自定义密码,然后检查它们是否符合特定条件,在这种情况下; 1. 必须在 9 到 15 个字符之间。 2. 必须有 2 个或多个大写和小写字符。 3. 必须有 2 个或更多数字。 4. 必须包含 1 个或多个符号。
我的问题是我似乎没有正确比较字符串,因为当我运行它时它说 “您的字符串包含 0 个小写字母、0 个大写字母、0 个符号、0 个数字”等。我认为这是因为它没有通过 if 语句的要求。我尝试改用 strcmp,但没有成功。
(请耐心等待,因为我对 C 很陌生)
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
char upCase [] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
char lowCase [] = {"abcdefghijklmnopqrstuvwxyz"};
char numbers [] = {"1234567890"};
char symbols [] = {"!#$%&'()*+-./:;<=>?@[\]^_`~"};
char passwordCheck [15+1];
int numCount = 0;
int lCaseCount = 0;
int uCaseCount = 0;
int symbolCount = 0;
int i = 0;
int randLCase, randNum, randUCase, randSymbol;
int charCount = 0;
void main()
{
fflush(stdin);
printf("\nEnter your password for checking: ");
scanf("%s", passwordCheck); // reads number
if (strlen(passwordCheck) > 15)
{
printf("'%s' is too long.\nIt must be between 9 and 15 characters", passwordCheck);
}
else if (strlen(passwordCheck) < 9)
{
printf("'%s' is too short.\nIt must be between 9 and 15 characters", passwordCheck);
}
else
{
int j;
int upCaseCheck, lowCaseCheck, symbolCheck, numCheck;
printf("Checking password '%s'..\n", passwordCheck);
for (j = 0 ; j >= strlen(passwordCheck); j++)
{
// check amount of uppercase characters in user's password
for (upCaseCheck=0; upCaseCheck <= strlen(upCase); upCaseCheck++)
{
if (passwordCheck[j] == upCase[upCaseCheck])
{
uCaseCount++;
}
}
// check amount of lowercase characters in user's password
for (lowCaseCheck=0; lowCaseCheck <= strlen(lowCase); lowCaseCheck++)
{
if (passwordCheck[j] == lowCase[lowCaseCheck])
{
lCaseCount++;
}
}
// check amount of numbers in user's password
for (numCheck=0; numCheck <= 15; numCheck++)
{
if (passwordCheck[j] == numbers[numCheck])
{
numCount++;
}
}
// check amount of symbols in user's password
for (symbolCheck=0; symbolCheck <= strlen(symbols); symbolCheck++)
{
if (passwordCheck[j] == symbols[symbolCheck])
{
symbolCount++;
}
}
} // end outer for
printf("Your password %s contains:\n %d numbers\n %d uppercase letters\n %d lowercase numbers\n %d symbols",
passwordCheck, numCount, uCaseCount, lCaseCount, symbolCount);
fclose(fp);
printf("\n\n");
system("pause");
}
提前感谢您提供的任何帮助。
【问题讨论】:
-
外部for循环有问题..它没有进入条件。将其更改为 j
-
我真的很讨厌那些对密码进行愚蠢限制的程序。请不要那样做。 15 个字符太少,如果我有 20 个字符的小写密码,它不会自动不安全。
-
[OT]:您可以为每个检查创建一个函数。
-
您是否尝试过调试您的问题?这不会立即表明你的错误吗?
-
您可以(并且应该,我相信)使用 C 标准函数,例如
isupper()、islower()、isdigit()(来自ctype.h)来进行这些字符类型检查。