I\'ve been working on a hangman game in c, and ive run into some trouble. Curren
ID: 3547480 • Letter: I
Question
I've been working on a hangman game in c, and ive run into some trouble. Currently i have a word bank built into my program, but i would like to read in words from a txt file and use those instead. I'm just not sure how to do that. Any help would be much appreciated! I know how to read in words from a file, but im not sure how to get from reading them in to having my program randomly select one from the file. Here's my code so far:
#include <stdio.h>
#include<string.h>
#include <stdlib.h>
#include <time.h>
int randof12(); //function prototype
char *list[12]={
"apple", "banana",
"computer", "orange",
"curios", "christmas",
"apathy", "project",
"programmer", "apartment",
"iphone", "facebook"
};
int main()
{
int wordi, lives=8;
char word[25];
int x,correct,i = 0;
int length;
char symb;
srand((unsigned int)time(NULL));
printf(" Welcome to word game. You have %d lives ", lives);
wordi = randof12();
length = strlen(list[wordi]);
for(x=0;x<length;x++)
{
word[x] = '-';
}
word[length] = 0;
printf("%s ",word);
while ((lives>0) && (i < length))
{
correct = 0;
printf("Enter a letter: ");
do{
scanf("%c", &symb);
symb = tolower(symb);
if((symb > 32) && ((symb < 97) || (symb > 122))) //insure that the charcter entered is valid
{
printf("Invalid character Enter a letter: ");
}
}while((symb < 97) || (symb > 122)); //parameters for a lower case letter
for(x=0;x<length;x++)
{
if(symb == word[x])
{
printf("This character already used. ");
break;
}
}
if(x==length)
{
printf("%c, %s ",symb,list[wordi]); // Uncomment to test program
for(x=0;x<length;x++)
{
if(symb == list[wordi][x])
{
word[x] = symb;
i++;
correct = 1;
}
}
if(correct == 0)
{
lives--;
if(lives > 0)
{
printf(" Wrong. %i lives left. ",lives);
}
else
{
printf(" You lose. :( ");
}
}
else
{
if(i < length)
{
printf(" Correct. ");
}
else
{
printf(" You win! :) ");
}
}
printf(" You correctly guessed: %s ",word);
}
}
return 0;
}
//function
int randof12(){
return rand() % 12;
}
Explanation / Answer
FILE *fopen(), *fp;
int c;
fp = fopen("inputfile.txt","r");
c = getc(fp);
//Assuming you know the number of words in tht file Let it ne n.
int n = 100;
char readword[20];
int randomReadIndex = rand()%n;
for(i = 0;i<n-1;i++) fcanf(fp,"%s",readword);
fcanf(fp,"%s",readword);
fclose(fp);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.