0

Program uses rand() function to generate random index. But it always produces same string no matter what! Why won't this work?

void rand_string()
{
    int a[10];
    int i;
    char b[] = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM";
    printf("%d", sizeof(b) / sizeof(b[0]));

    for(i = 0; i < 10; i++)
    {
        int gen_rand = rand() % 63; 
        a[i] = b[gen_rand];
    }

    for(i = 0; i < 10; i++)
        printf("%c", a[i]);
}
0726
  • 315
  • 2
  • 13
  • 1
    You forgot `srand()`. – HolyBlackCat Aug 19 '17 at 17:02
  • 1
    Totally unrelated to your problem, but `sizeof(char)` is specified to *always* be `1`. That means `sizeof(b)` is all you need. Also remember that the size includes the terminating null character `'\0'`. I also recommend you use the size (-1 to remove the terminator) for the modulo operation, please avoid [*magic numbers*](https://en.wikipedia.org/wiki/Magic_number_(programming)). Lastly, if your goal is to generate something which can be used as a string, then don't forget the terminator in `a`. – Some programmer dude Aug 19 '17 at 17:05
  • Google is your friend. Go to Google and enter "same random number every time", open the first link and upvote the question and the working answer. Stack Overflow is about having others having asked the same questions already so that you do not have to ask them again. – Antti Haapala -- Слава Україні Aug 19 '17 at 19:17

2 Answers2

1

Use srand function to seed the random generator

srand((unsigned)time(NULL));

Note that you only have to seed once in your program otherwise it will not work properly.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
haccks
  • 104,019
  • 25
  • 176
  • 264
0

You could firstly define a random function specific to your needs, i.e. generating in specific range (the length of the current string), like so:

int random(int min, int max) 
{ 
    return min + (rand()) / (RAND_MAX / (max - min)); 
}

then in your string-random-generator function you could also add a random length to every string:

void rand_str()
{
    static const char alphanum[] =
    "0123456789"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz";  // define only on first call

    // call srand() using #include <time.h> ; could be outside of function, i.e. in main()

    int length = random(0, 10);   // get random length in [0, 10] on each call

    // use length and random(0, sizeof(alphanum) / sizeof(alphanum[0])) in for loop

    // everything else is the same...
}

use the keyword static to indicate single1 definition of the array alphanum (think of it that it is like making it global) and call function srand() once, before the use of random().


Note: you should consider modifying your function to a single purpose, i.e. only generating a random string and returning (a pointer to) a string; and printing it in a separate function.


1. Only on the first call of rand_str().

Ziezi
  • 6,375
  • 3
  • 39
  • 49