c - 如何用 C 创建一个随机字符串?
问题描述
我想在 C 中生成一个随机字符串。
我要生成的地方<HERE>
在代码中。
#include <stdio.h>
#include <string.h>
int main(int argc, char * argv[]) {
if (argc == 2) {
printf("Checking key: %s\n", argv[1]);
if (strcmp(argv[1], "AAAA-<HERE>") == 0) {
printf("\033[0;32mOK\033[0m\n");
return 0;
} else {
printf("\033[0;31mWrong.\033[0m\n");
return 1;
}
} else {
printf("USAGE: ./main <KEY>\n");
return 1;
}
return 0;
}
解决方案
一种简单的方法是定义一个包含您在随机字符串中接受的所有字符的字符串,然后从该字符串中重复选择一个随机元素。
#include <time.h> // for time()
#include <stdlib.h> // for rand() & srand()
...
srand (time (NULL)); // define a seed for the random number generator
const char ALLOWED[] = "abcdefghijklmnopqrstuvwxyz1234567890";
char random[10+1];
int i = 0;
int c = 0;
int nbAllowed = sizeof(ALLOWED)-1;
for(i=0;i<10;i++) {
c = rand() % nbAllowed ;
random[i] = ALLOWED[c];
}
random[10] = '\0';
...
请注意,使用rand()
不是生成随机数据的加密安全方式。
编辑:根据 Lundin 评论将 strlen 替换为 sizeof 。
推荐阅读
- svn - 不要跟踪对配置文件的更改
- python - sqlite3.OperationalError:无法识别的令牌:“7nbtkq”
- flutter - Flutter ToggleButton 类 - Flutter 1.9.1
- django - 如何实现以下目标。?
- android - 重新安装应用后不会删除 Parse 当前用户
- android - Android onCreate extras
- visual-studio-2015 - SSIS ScriptResults.Failure vs Dts.Events.FireError - 默认行为?
- javascript - 修复创建粘性滚动导航栏时的“跳转”
- spring-boot - Intellij Spring Boot 项目运行配置
- windows - cd是什么意思。> 在 Windows CMD 中创建空文件?