What is wrong with the code? #include \"stdio.h\" #include \"stdlib.h\" #include
ID: 3767927 • Letter: W
Question
What is wrong with the code?
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "time.h"
#define RAND_MAX 50
int main() {
FILE *file;
int i, j;
size_t count, n;
char word[25];
srand(time(NULL));
file = fopen("words.txt", "r");
if (file == NULL){
printf("The file cannot be opened. ");
return 1;
}
count = 0;
while(1==fscanf(file, "%24s", word)){
if(count == 6)
break;
strcpy(guessWords[count++], word);
}
fclose(file);
n = count;
if(n > RAND_MAX){
int part;
size_t random = 0;
i = n / RAND_MAX;
part = rand() % (i+1);
if(part == i){
j = n % RAND_MAX;
if(j != 0)
random = random + RAND_MAX*part + rand() % j;
else
random = random + RAND_MAX*(part-1) + rand();
} else {
random = random + RAND_MAX*part + rand();
}
printf("%s ", guessWords[random]);
} else {
int random = rand() % n;
printf("%s ", guessWords[random]);
}
// index for random word
int randomIndex = rand() % 6;
int numLives = 5;
int numCorrect = 0;
int oldCorrect = 0;
int lengthOfWord = strlen(guessWords[randomIndex]);
// 0 1 2 3 4 5
// p u r p l e
// letterGuessed[8] = { 0,0,0,0,0,0,0,0 };
int letterGuessed[8] = { 0,0,0,0,0,0,0,0 };
int quit = 0;
int loopIndex = 0;
int reguessed = 0; // EDIT
char guess[16];
char letterEntered;
// game loop
while ( numCorrect < lengthOfWord ) {
printf(" New Turn.... Hangman Word:");
for( loopIndex = 0; loopIndex < lengthOfWord; loopIndex++) {
if(letterGuessed[loopIndex] == 1) {
printf("%c",guessWords[randomIndex][loopIndex]);
} else {
printf("-");
}
}
printf(" ");
printf("Number Correct So Far:%d ",numCorrect);
printf("Enter a guess letter:");
fgets(guess, 16, stdin);
if( strncmp(guess, "quit", 4) == 0) {
quit = 1;
break;
}
letterEntered = guess[0];
reguessed = 0;
printf("letterEntered:%c ",letterEntered);
oldCorrect = numCorrect;
for( loopIndex = 0; loopIndex < lengthOfWord; loopIndex++) {
if(letterGuessed[loopIndex] == 1) {
if(guessWords[randomIndex][loopIndex] == letterEntered) {
reguessed = 1;
break;
}
continue;
}
if( letterEntered == guessWords[randomIndex][loopIndex] ) {
letterGuessed[loopIndex] = 1;
numCorrect++;
}
}
if( oldCorrect == numCorrect && reguessed == 0) {
numLives--;
printf("Sorry, wrong guess ");
if (numLives == 0) {
break;
}
} else if( reguessed == 1) {
printf("Already Guessed!! ");
} else {
printf("Correct guess :) ");
}
} // while loop
if( quit == 1 ) {
printf(" the user quit early ");
} else if (numLives == 0) {
printf(" Sorry you lose, the word was: %s ",
guessWords[randomIndex]);
} else {
printf(" YOU WIN!!! :) ");
}
return 0;
}
Explanation / Answer
you are not defining guesswords,and declaration is not allowed in middle you put a local function to execute random word.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.