我正在编写一个程序,允许用户输入自定义密码,然后检查他们是否满足特定条件,在这种情况下; 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 = 0 ; j >= strlen(passwordCheck); j++)
立即为假,因此不会执行此循环内的所有内容。
然后,要“探索”一个从 0 到它的最后一个字符的字符串,检查是
for (j = 0; j < length; j++)
而不是 <=
.
关于c++ - 比较C中两个字符串的每个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20924341/