在C中生成随机字符串无符号字符

Jua*_*uan 4 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));

}
Run Code Online (Sandbox Code Playgroud)

Ale*_*exD 5

也许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;
Run Code Online (Sandbox Code Playgroud)