gpt4 book ai didi

c - 在 C 中为密码添加随机符号

转载 作者:太空宇宙 更新时间:2023-11-03 23:50:29 25 4
gpt4 key购买 nike

到目前为止,该程序输出一个包含 5 个大写字符、5 个小写字符和 2 个数字的密码。但我也想从列表中添加一个随机符号,例如 !£$%^&*()+= <>?/@我可以像数字和字符一样在for循环中添加吗?

到目前为止,这是我的代码:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

FILE*fp;

int main(void) {

char password[5 + 5 + 2 + 1];
int i, j=0, len=sizeof(password)-1;
int menuNum = 0;


fp = fopen("passwords.txt", "a+");
//Opens the text file to save the Passwords

srand(time(NULL));
printf(" Main Menu\n");
printf("********************************\n");
printf("\nEnter 1 to Generate a New Password: ");
printf("\n\n");
printf("Enter 2 to Check Old Passwords: ");
printf("\n\n");
printf("Enter 3 to Exit. ");
printf("\n\n");
scanf("%d", &menuNum); // reads number

if (menuNum == 1)
{
printf("********************************\n");
printf("\nYour New Password is: \n\n");

//Each Password will Have 13 Characters(5 Upper, 5 Lower, 2 Numbers & 1 Symbol)

for (i = 0; i < 5; ++i)
password[j++] = 'a' + rand() % ('z' - 'a' + 1); //Generates 5 random Lowercase characters

for (i = 0; i < 5; ++i)
password[j++] = 'A' + rand() % ('Z' - 'A' + 1); //Generates 5 random Uppercase characters

for (i = 0; i < 2; ++i)
password[j++] = '0' + rand() % ('0' - '9' + 1); //Generates 2 random numbers

password[j] = '\0';
for(i = 0; i < sizeof(password)-1; ++i)
{
char c = password[i];
j = rand() % len;
password[i] = password[j];
password[j] = c;
}

printf("%s\n\n", password);
printf("********************************\n");
fprintf(fp, "\n%s", password); //Outputs the Generated Passoword to the text file
fclose(fp); //Closes the text file
system("pause");
}

最佳答案

使用这样的东西:

char *special_stuff = "!$%^&*()+=<>?/@";

...
password[j++] = special_stuff[rand() % strlen(special_stuff)];

(我删除了 £ 字符,因为它可能会给您带来各种问题,例如,被多字节编码)。

关于c - 在 C 中为密码添加随机符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20939607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com