Search code examples
c++randomchardigit

Generate random char/digit


I`m trying to found fastest way to generate random digit/char array.

char *randomGet(int num) {
    srand(time(NULL));
    const char ab[37] = { "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ" };//Alphabet&Digit
    char *targ = new char[num];
    for (int i = 0; i < num; i++) {
        strcat(targ, ab[rand() % 38]);
    }
    return targ;
}

So far I've come up with this, but it does not work (argument of type char is incompatible with parameter of type const char *). Help me find the best solution to my problem. Ty.


Solution

  • strcat() takes a char* as input, but you are giving it a single char instead, thus the compiler error.

    Also, the buffer that strcat() writes to must be null terminated, but your targ buffer is not null terminated initially, and you are not allocating enough space for a final null terminator anyway.

    You don't need to use strcat() at all. Since you are looping anyway, just use the loop counter as the index where to write in the buffer:

    Also, you are using the wrong integer value when modulo the return value of rand(). You are producing a random index that may go out of bounds of your ab[] array.

    Try this instead:

    char *randomGet(int num)
    {
        srand(time(NULL));
        static const char ab[] = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ"; //Alphabet&Digit
        char *targ = new char[num+1];
        for (int i = 0; i < num; ++i) {
            targ[i] = ab[rand() % 36];
        }
        targ[num] = '\0';
        return targ;
    }