Posted: . At: 10:17 AM. This was 3 years ago. Post ID: 15028
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.


An improved version of my random text C program.


This is an improved version of my random monster program. This shows how to get the size of a const char array and then select a random entry from the array.

monsters.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
char *cuserid(char *s);
 
const char* x[] = {
    "Baron of Hell", "Demon", "Hellknight",
    "Cyberdemon", "Mancubus", "Revenant",
    "Heretic Imp", "Zombieman", "Sergeant",
    "Beholder", "Moloch", "Satyr",
    "Afrit", "Ettin", "Maulator",
};
 
int cool(void) {
    int k;
 
    size_t i = sizeof(x) / sizeof(x[0]);
    k = 0;
    srand((unsigned)time(NULL));
    k = rand() % i;
    return k;
}
 
int main() {
 
  char myname[128];
  char *player;
  cuserid(myname);
 
  printf("%s was slaughtered by a %s.\n",myname , x[cool()]);
 
  return 0;
}

This section of code gets the proper size of the x[] array.

size_t i = sizeof(x) / sizeof(x[0]);
<pre>
 
This function gets a random number that will equate to an entry in the array.
 
<pre lang="c" line="1">
int cool(void) {
    int k;
 
    size_t i = sizeof(x) / sizeof(x[0]);
    k = 0;
    srand((unsigned)time(NULL));
    k = rand() % i;
    return k;
}

Then in the main() we can call printf(3) to print a random entry.

  printf("%s was slaughtered by a %s.\n",myname , x[cool()]);

This is quite simple, but I need to find a random number function that generates numbers faster, still, it is adequate for my needs in this example.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.