我编写了一个密码生成器,但它有时似乎表现得很笨拙。当我启动程序时,有时会得到如下输出:
password: pyi>Sx2Z
我实际上排除了“大于”字符。我什至打印了池中的每个可用字符,并且没有出现“大于”字符。我有一点困惑。我感谢任何帮助或解释。提前致谢。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define STARTNUMBER '0'
#define ENDNUMBER '9'
#define STARTUPLETTER 'A'
#define ENDUPLETTER 'z'
#define STARTLOWLETTER 'a'
#define ENDLOWLETTER 'z'
#define SIZE (2*26+10)
#define DEBUG
int main(int argc, char** argv)
{
srand(time(0));
int defaultLenght = 8;
if(argc == 2)
{
defaultLenght = atoi(argv[1]);
}
char pool[SIZE];
char password[defaultLenght];
char digitCount = ENDNUMBER - STARTNUMBER + 1;
for(int c = 0; c < digitCount; c++)
{
pool[c] = STARTNUMBER + c;
}
char upLetterCount = ENDLOWLETTER - STARTUPLETTER + 1;
for(int c = 0; c < upLetterCount; c++)
{
pool[digitCount + c] = STARTUPLETTER + c;
}
char lowLetterCount = ENDLOWLETTER - STARTLOWLETTER + 1;
for(int c = 0; c < lowLetterCount; c++)
{
pool[digitCount + lowLetterCount + c] = STARTLOWLETTER + c;
}
#ifdef DEBUG
for(int i = 0; i < SIZE; i++)
{
printf("%c", pool[i]);;
}
printf("\r\n");
#endif
printf("password: ");
for(int i = 0; i < defaultLenght; i++)
{
int index = rand() % SIZE + 1;
password[i] = pool[index];
pool[index] = pool[SIZE -i -1];
putchar(password[i]);
}
printf("\r\n");
return(0);
}
使用随机索引选择入池有错误
int index = rand() % SIZE + 1;
它给出了 1..SIZE
范围内的数字,但池需要 0..(SIZE-1)
范围内的索引。这可能会导致选择数组之外的下一个字符。所以那一行应该是
int index = rand() % SIZE;
但是您的密码选择还有一个问题。您用池数组中的另一个字符覆盖所选字符,大概是为了防止它被选中两次,但您没有减小池的大小。我建议这样做:
int poolsize = SIZE;
for(int i = 0; i < defaultLenght; i++)
{
int index = rand() % poolsize;
password[i] = pool[index];
pool[index] = pool[--poolsize];
putchar(password[i]);
}
我是一名优秀的程序员,十分优秀!