【发布时间】:2015-04-27 08:58:50
【问题描述】:
我想用下面的代码生成一个长度为 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));
}
【问题讨论】:
-
如果您还不熟悉 ascii,您可能想了解一下,有很多 ascii 代码不是非典型字符串
-
注:
text[i] = (unsigned char) rand() & 0xfff;和text[i] = ((unsigned char) rand()) & 0xfff;不一样吗?那么为什么& 0xfff? -
小点:1) Unix
srandom()与random()一起使用,std Csrand()与rand()一起使用。 2) 考虑size_t LEN而不是int。
标签: c