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

标签 c

到目前为止,该程序输出一个包含 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/

相关文章:

c++ - 如何解决 libmysqlclient_r.so 符号引用链接错误?

在 C 中创建结构体数组

c - Solaris 11/Illumos/OmniOS : Which package has/usr/include/sys/types. h?

c - 从文件中读取txt,将其切成单词并显示

c - 如何使用 linux distro : ubuntu 16. 04 在 c 中使用 API

c++ - 我们什么时候需要在 c 中进行深度复制

c - Linux;如果您不是 root,请将 UID 更改为 root

c - 一种编程语言如何调用另一种语言编写的库?

c - C 中的锯齿状数组 - 一种更有效的方法?

c++ - SDL Surface 返回 NULL?