Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
sorry for the question is too long, I've tried to make the other parts of hangman game , but I do not understand how to make a list of words through external files such as txt, list of words written in the file and will be loaded in compilier, but should be incorporated into the array first, that fast loaded, word must at random, please help to do it in the language of c, is established in a void
Posted

1 solution

As a simple approach, you could write a text file with just one word per line, then read the words into an array, eventually shuffling the array itself, e.g.

C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_WORDS 1000
#define MAX_LEN 256

void shuffle(char * pword[], int words, int iterations)
{
  int n;

  if ( words <= 1) return;

  for (n=0; n<iterations; n++)
  {
    int i1, i2;
    i1 = rand()%words;
    i2 = rand()%words;
    char * tmp = pword[i1];
    pword[i1] = pword[i2];
    pword[i2] = tmp;
  }
}

int main()
{
  int n;
  char buf[MAX_LEN];
  char * pword[MAX_WORDS];
  int words = 0;

  FILE * fp = fopen("words.txt", "r");

  if ( ! fp ) return -1;

  while (!feof(fp))
  {
    if (words == MAX_WORDS) break;
    if (! fgets(buf, MAX_LEN, fp) ) break;
    buf[strlen(buf)-1] = '\0'; // remove newline
    pword[words] = strdup(buf); // this dynamically allocates memory
    words++;
  }
  fclose(fp);

  shuffle(pword, words, 2*words);

  for (n=0; n<words; n++)
    printf("%s\n", pword[n]);

  // cleanup
  for (n=0; n<words; n++)
    free( pword[n]);

  return 0;
}


The above program reads the file:

aaaaaaaaaaa
bbbbbbbb
cccccccccc
dd
eeeeeeeeeee
fffff
gggggggggggg
hhhhhhhhh
iiiiiiiiiii
jjjjjjjjjj
k
llllllllll
mmmmmmmm
nnnnnnn
ooooooo
p
qqqqqq
rrrrrrrr
sssss
tt
uuuuuu
vvvvvvv
wwwwwww
xxxxxxxxx
yyyyyyyyyyy
z


Producing the following output:


jjjjjjjjjj
aaaaaaaaaaa
rrrrrrrr
fffff
cccccccccc
sssss
qqqqqq
llllllllll
bbbbbbbb
nnnnnnn
uuuuuu
xxxxxxxxx
iiiiiiiiiii
hhhhhhhhh
eeeeeeeeeee
z
dd
k
wwwwwww
tt
mmmmmmmm
vvvvvvv
yyyyyyyyyyy
p
gggggggggggg
ooooooo
 
Share this answer
 
Comments
arkhandio 1-Dec-12 11:01am    
thank you, one more question, if i want to pick one word form this void to the hangman game, what should i write? and void in what parameters should I have?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900