【问题标题】:Issue with a nested for loop嵌套 for 循环的问题
【发布时间】:2012-01-13 02:42:58
【问题描述】:

我目前正在开发一个要求用户输入密码的程序。然后将用户的输入与文本文件中的单词列表进行比较。用户有 3 次机会输入单词。如果正确,程序将重新开始循环。这种情况一直持续到所有单词都被正确猜到为止。如果一个单词被猜错了 3 次,程序应该终止。我的问题在于 3 个猜测循环。如果它没有嵌套在while 循环中,我可以让它工作,但是使用while 循环它会继续要求输入不正确的单词。我错过了什么?这是我的代码:

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

【问题讨论】:

    标签: c for-loop nested-loops


    【解决方案1】:

    当您执行break 时,您会脱离for 循环,但不会脱离while 循环。

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

    【讨论】:

    • 我知道 break 函数不正确,我对它们并不完全熟悉。我基本上想要它,这样当用户猜到正确的单词时,整个循环会重新开始,但不知道如何格式化。
    • 非常感谢您的意见,非常感谢
    【解决方案2】:

    提示:如果用户有 3 次未命中,则 for 循环后 i 的值将等于 3。这是你做某事的机会(终止程序)。

    【讨论】:

    • 感谢您的意见,非常感谢。
    【解决方案3】:

    您没有在以下部分中中断:

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

    【讨论】:

    • 这是有效的确切代码。我知道这是一件相对简单的事情,我只是无法理解它。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多