generating random printable ascii characters in c
i'm trying to write a program for testing purposes that generates a sequence of pseudo-random printable ASCII characters, where you put in the command line how many characters you want. right now it's not working so well; the sequence is almost always majority ?s, and it doesn't开发者_如何学编程 always print the number of characters i tell it to print. here's my code; what's wrong with it? i use the time as a seed for the random function.
note: it's not worth it to me to use any algorithm more complicated than one using srand() and rand().
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[]) {
int c;
int i;
int limit;
sscanf(argv[1], "%d", &limit);
srand((unsigned int)time(NULL));
for (i = 0; i < limit; i++) {
c = rand();
if (c != 9 && c != 10 && c <= 32 && c >= 127) {
i--;
}
else {
putchar(c);
}
}
return 0;
}
thanks!
Try fixing this line:
if (c != 9 && c != 10 && c <= 32 && c >= 127) {
should be:
if (c != 9 && c != 10 && (c < 32 || c >= 127)) {
But this would probably be better:
if (!isprint(c)) {
精彩评论