I\'ve been working on a hangman game in c, and ive run into some trouble. Curren
ID: 3546909 • 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! 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
Use this snippet might be useful!
#include <stdio.h>
#include <stdlib.h>
int main()
{
char list[100][100];
int n = 0;
FILE *file = fopen("input.txt", "r");
if (!file) return -1; //error
while (feof(file)) {
scanf("%s", &list[n++]);
}
fclose(file);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.