将用户输入与文本文件进行比较并在C中循环

时间:2011-12-02 00:16:13

标签: c loops file-io

我正在创建一个程序,要求用户输入一个单词。然后将该单词与文本文件中的单词进行比较。如果正确,我希望用户输入另一个与文本文件中的下一个单词相对应的单词,这应循环到文件末尾。我遇到了循环到文件末尾的问题。请问有人可以查看我的代码并给我一些指示吗?非常感谢

#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, count;

    //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//

    fscanf(fp,"%s", secret);
    //Need to create a loop here that will read the text file 20 times, 
    // each time reading the next word//
    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");
            return 0; //This return will terminate the program. 
                      // I need to restart loop from here
        }
        else
        {
            printf("Your guess was incorrect. Please try again\n");
        }
    }
    return 0;
}

2 个答案:

答案 0 :(得分:1)

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

int main(void)
{
    FILE *fp = fopen("secretwords.txt", "r");   
    if (fp == NULL)
    {
        printf("Error reading file\n");
        return 1;   
    }

    char guess[20] = {0};
    char secret[20] = {0};
    while(fscanf(fp, "%s", secret) != EOF) // i would suggest you use 'fscanf_s("%s", guess);' instead if available
    {
        printf("Please guess the word: \n");
        scanf("%s", guess); // i would suggest you use 'scanf_s("%s", guess);' instead if available

        if (!strncmp(secret, guess, sizeof(guess)))
        {
            printf("Your guess was correct. Continue ...\n");           
        }
        else
        {
            printf("Your guess was incorrect. Good bye.\n");
            break;
        }
    }
    fclose(fp);

    return 0;
}

我就scanf_sfscanf_s提出了一些建议,如果可以的话,请使用它们。但是,我仍然想知道为什么他们仍然在学校教授不良代码?我根本不建议使用*scanf*函数。进一步阅读:uncontrolled format string

答案 1 :(得分:0)

  • 将从文件中读取的fscanf调用移动到返回下一个字的函数
  • 循环用于用户输入,只需要调用上面列出的功能,当你需要前进到文件中的下一个单词时(当用户输入正确的东西时)