我目前正在研究一個程序,要求用戶輸入一個祕密詞。然後將用戶的輸入與文本文件上的單詞列表進行比較。用戶有三次機會輸入該單詞。如果正確,程序將重新啓動循環。這一直持續到所有單詞都被正確猜測。如果一個單詞錯誤地被猜到了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;
}
這是工作的確切代碼。我知道這是一件相對簡單的事情,我無法理解它。非常感謝。 – adohertyd