在 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)=%zdn", 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;

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

  1. 首先,如果要生成长度为 100 的字符串,则需要声明一个大小为 101 的数组。

    int i, LEN = 101;
    srandom(time(NULL));
    unsigned char text[LEN];
    
  2. 当你将调用中的字符分配给rand时,请确保它不是0的,这通常是字符串的空终止符。

    for (i = 0; i < LEN - 1; /* Don't increment i here */) {
        c = (unsigned char) rand() & 0xfff;
        if ( c != '' )
        {
           text[i] = c;
           // Increment i only for this case.
           ++i
        }
    }
    

    并且不要忘记 null 终止字符串。

    text[LEN-1] = '';
    

最新更新