在C中生成随机字符串unsigned char(Generating random string unsigned char in C)

系统教程 行业动态 更新时间:2024-06-14 16:59:47
在C中生成随机字符串unsigned char(Generating random string unsigned char in C)

我想用下面的代码生成长度为100的随机字符串文本,然后验证是否打印了变量文本的长度,但有时小于100.我该如何解决这个问题?

#include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> int main() { int i, LEN = 100; srandom(time(NULL)); unsigned char text[LEN]; memset(text, 1, LEN); for (i = 0; i < LEN; i++) { text[i] = (unsigned char) rand() & 0xfff; } printf("plain-text:"); printf("strlen(text)=%zd\n", strlen(text)); }

I want to generate a random string text of length 100 with the code below, then to verify that I print the length of the variable text but sometimes that is less than 100. How can I fix that?

#include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> int main() { int i, LEN = 100; srandom(time(NULL)); unsigned char text[LEN]; memset(text, 1, LEN); for (i = 0; i < LEN; i++) { text[i] = (unsigned char) rand() & 0xfff; } printf("plain-text:"); printf("strlen(text)=%zd\n", strlen(text)); }

最满意答案

也许随机字符0被添加到字符串中,然后它被strlen认为是字符串的结尾。

您可以生成随机字符(rand() % 255) + 1以避免零。

最后,你必须对字符串进行零终止。

LEN = 101; // 100 + 1 .... for (i = 0; i < LEN - 1; i++) { text[i] = (unsigned char) (rand() % 255 + 1); } text[LEN-1] = 0;

Perhaps a random character 0 was added to the string, and then it is considered as the end of string by strlen.

You can generate random characters as (rand() % 255) + 1 to avoid zeros.

And at the end you have to zero-terminate the string.

LEN = 101; // 100 + 1 .... for (i = 0; i < LEN - 1; i++) { text[i] = (unsigned char) (rand() % 255 + 1); } text[LEN-1] = 0;

更多推荐

本文发布于:2023-04-17 09:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/7fc0041fd9939196ed3d1db84ef39457.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   unsigned   char   string   random

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!