Randomly choosing a word from a text file in C
I'm quite new at programming and I'm trying to code Hangman. I have 10 words saved in a textfile in the same folder as the code and I want the program to randomly choose a word and save that word into a character array.
I've googled and looked around but I can't seem to figure out how to do it. Do I use something like fopen() and rand()?
assuming the words are written one per line , here's a small piece of code that'll do that :
FILE* fp = NULL; char words; int i = 0 , ran = 0; srand(time(NULL)); fp = fopen("path" , "r+"); for(; fgets(words , sizeof(words) , fp) ; i++) ; ran = rand() % i; rewind(fp); for(i = 0 ; i < ran ; i++) fgets(words , sizeof(words) , fp); printf("%s\n" , words);
beware of not having a new line character at the end of you file because it will be considered as a word and will sometimes be returned to you
It depends on how these words are saved in a file. My first thought is to choose random number and then read a word which is written in a line that has chosen number. But your words have to be written one per line.
You can do this in three steps:
Read all words from file to char words[N] (here N=10). In C, you can do this as follows:
char words; int i = 0; while(10>i && fgets( words[i++], 100, file) );
Generate a random number i within [0,N-1].
int i = rand() % 10;