How can I assign the file to an array and print a random word from it?
A) read the file once to get parameters: 1: number of words, 2: length of longest word (used for memory alloc later)
B) Allocate memory for an array of strings (eg: char **strings;
) to read file into.
(note: you have choosen to use char words[540000][25];
, which will also work, but is not flexible)
C) Using fopen()
and fgets()
read each word into array strings
.
D) Use srand()
and rand()
to produce pseudo random number from 0 to numWords.
(Note: rand()
by itself only produces numbers from 0 to RAND_MAX (32767). If bigger number needed, adapt to that by using combinations of rand()
to produce a bigger number.
E) Use printf("Random word is %s", strings[randNum]);
to print random number.
Your code segment is a start, but you are missing a few key elements. One of which is shown here:
At this point in your code:
random = rand();
fprintf(file, "%lf\n", random);
fclose(file);
You still have not read the words from the opened file into a string array words
, as you stated you wanted to. That should be done before this last section. Something like this should work:
#define DELIM "- .,:;//_*&\n" //or use char DELIM[]="- .,:;//_*&\n"
//...other code
char *buf;
char line[260];
int cnt=0;
while(fgets(line, 260, file))
{
buf = strtok(line, DELIM);
while(buf)
{
if((strlen(buf) > 0) && (buf[0] != '\t') && (buf[0] != '\n') && (buf[0] != '\0')&& (buf[0] > 0))
{
strcpy(words[cnt++], buf);
}
buf = strtok(NULL, DELIM);
}
}
//... other code