【发布时间】: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