1
votes

I'm currently working on a program that asks a user to enter a secret word. The user's input is then compared with a list of words which are on a text file. The user has 3 chances to enter the word. If correct, the program restarts the loop. This continues until all the words have been guessed correctly. If a word is incorrectly guessed 3 times, the program should terminate. My problem is with the 3 guesses loop. I can get it to work if it is not nested in the while loop however with the while loop it's continues to ask for the incorrect word. What am I missing? Here is my code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
   //Step 1: open file and declare variables//
   FILE *fp;
   fp = fopen("secretwords.txt","r");
   char guess[20];
   char secret[20];
   int i;

   //Step 2: Check that file opened correctly, terminate if not//
   if (fp == NULL) 
   {
      printf("Error reading file\n");
      exit (0);
      fclose(fp);
   }
   //Step 3: Create loop to run for each word to run to end of file//

   while(fscanf(fp,"%s", secret)!=EOF)
   {         
      for (i=0; i < 3; i++)
      {
         printf("Please guess the word: \n");
         scanf("%s", guess);

         if (strcmp(secret,guess)==0)
         {
            printf("Your guess was correct\n");
            break;
         }

         else
         {
           printf("Your guess was incorrect. Please try again\n");
         }
      }   
   }
   return 0;
}
3

3 Answers

3
votes

When you do break, you break from the for loop, but not from the while loop.

To solve it, you can either change the design to have one loop only, or you should have the break instruction in the outer loop too.

1
votes

Hint: if the user has had 3 misses, the value of i after the for loop will equal to 3. This is your chance to do something (terminate the program).

1
votes

You did not do break in the following part:

else
{
    if(i == 2)
        break;
    printf("Your guess was incorrect. Please try again\n");
}