2011-12-05 177 views
1

我目前正在研究一个程序,要求用户输入一个秘密词。然后将用户的输入与文本文件上的单词列表进行比较。用户有三次机会输入该单词。如果正确,程序将重新启动循环。这一直持续到所有单词都被正确猜测。如果一个单词错误地被猜到了3次,程序应该终止。我的问题是3猜测循环。如果它不嵌套在while循环中,我可以使它工作,但是while循环会继续询问不正确的单词。我错过了什么?这里是我的代码:问题与嵌套for循环

#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; 
} 

回答

1

你没有做好以下几部分突破:

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

这是工作的确切代码。我知道这是一件相对简单的事情,我无法理解它。非常感谢。 – adohertyd

3

当你做break,你从for回路断线,而不是从while循环。

要解决这个问题,您可以将设计更改为只有一个循环,或者您也应该在外部循环中使用break指令。

+0

我有一个想法,中断功能是不正确的,我不完全熟悉他们。我基本上想要它,以便当用户猜测正确的单词整个循环再次开始,但不知道如何格式化。 – adohertyd

+0

用户在正确的猜测后继续。所以这部分是好的 – onemach

+0

非常感谢您的意见非常赞赏 – adohertyd

1

提示:如果用户有3次失败,for循环后的值为i将等于3.这是您做某事的机会(终止程序)。

+0

感谢您的意见,真的很感激。 – adohertyd