如何用C生成一个随机字符串?

如何用C生成一个随机字符串?,c,C,我想用C语言生成一个随机字符串 我要在代码中生成的位置是 #包括 #包括 int main(int argc,char*argv[]){ 如果(argc==2){ printf(“正在检查密钥:%s\n”,argv[1]); 如果(strcmp(argv[1],“AAAA-”==0){ printf(“\033[0;32mOK\033[0m\n”); 返回0; }否则{ printf(“\033[0;31mWrong.\033[0m\n”); 返回1; } }否则{ printf(“用法:./m

我想用C语言生成一个随机字符串

我要在代码中生成的位置是

#包括
#包括
int main(int argc,char*argv[]){
如果(argc==2){
printf(“正在检查密钥:%s\n”,argv[1]);
如果(strcmp(argv[1],“AAAA-”==0){
printf(“\033[0;32mOK\033[0m\n”);
返回0;
}否则{
printf(“\033[0;31mWrong.\033[0m\n”);
返回1;
}
}否则{
printf(“用法:./main\n”);
返回1;
}
返回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';
...
#包含//for time()
#包括//for rand()&srand()
...
srand(time(NULL));//为随机数生成器定义种子
允许的常量字符[]=“ABCDEFGHIJKLMNOPQRSTUVXYZ1234567890”;
字符随机[10+1];
int i=0;
int c=0;
int nbAllowed=sizeof(ALLOWED)-1;

对于(i=0;i而言,一种简单的方法是定义一个包含随机字符串中接受的所有字符的字符串,然后从该字符串中重复选取一个随机元素

#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';
...
#包含//for time()
#包括//for rand()&srand()
...
srand(time(NULL));//为随机数生成器定义种子
允许的常量字符[]=“ABCDEFGHIJKLMNOPQRSTUVXYZ1234567890”;
字符随机[10+1];
int i=0;
int c=0;
int nbAllowed=sizeof(ALLOWED)-1;

对于(i=0;除此之外,使用std::string,它将回答您的问题:除了使用std::string,它将回答您的问题:
strlen(允许)
->
sizeof(允许)-1
。我已经更新了我的答案。更一般地说,是否存在
sizeof
不起作用的情况,
strlen
是正确的选择?如果字符串是在运行时分配的,或者只有指向它的指针,则必须使用
strlen
。但是如果在编译时长度已知,并且字符串没有更改,则
strlen
的速度实在太慢了。
strlen(允许)
->
sizeof(允许)-1
。我已经更新了我的答案。更一般地说,是否存在
sizeof
不起作用的情况,
strlen
是正确的选择?如果字符串是在运行时分配的,或者只有指向它的指针,则必须使用
strlen
。但是如果在编译时长度已知,并且字符串没有更改,则