C 编程 - 函数从文本文件中读取 10 行并等待您进入后一个循环

C programing - function reads 10lines from text file and waits till you enter a latter loop

我得到了一个 assiment 来制作一个从文本文件中读取和显示 10 行的函数 然后停下来等你输入任意键然后再读10行直到它结束..

这就是我所做的

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

int main()
{
    FILE * source;
    char sentence[80];

    source = fopen("source.txt", "r");


    while (fgets(sentence, 80, source) != NULL)
    {
        for (int i = 0; i < 9; i++){
            fgets(sentence, 80, source);

            printf("%s", sentence);
        }


        printf("\n\n\n Press [Enter] key to continue.\n");


        while (getch() != NULL)
        {



            break;
        }

    }puts("\n\n\n .....DONE!!");

    fclose(source);

}

我的函数的问题是它多次重复最后一句话 因为 for 循环。

有什么想法吗?

为什么不

int i = 0;
while (fgets(sentence, 80, source) != NULL) //Breaks when fgets fails to read
{
    i++;
    printf("%s", sentence);
    if(i == 10) //10 lines read and printed
    {
        printf("\n\n\n Press [Enter] key to continue.\n");
        i = 0;  //Reset counter
        getch(); //Wait for key press
    }
}

如果您想等到用户按下 Enter,请使用

int i = 0;
while (fgets(sentence, 80, source) != NULL) //Breaks when fgets fails to read
{
    i++;
    printf("%s", sentence);
    if(i == 10) //10 lines read and printed
    {
        printf("\n\n\n Press [Enter] key to continue.\n");
        i = 0;
        while(getch() != 13); //Keep looping until enter is pressed
    }
}


另一种避免将 i 的值重置为 @LPs 的方法是:

int i = 0;
while (fgets(sentence, 80, source) != NULL) //Breaks when fgets fails to read
{
    i++;
    printf("%s", sentence);
    if(i % 10 == 0) // Same as `if(! (i % 10))` 
    {
        printf("\n\n\n Press [Enter] key to continue.\n");
        while(getch() != 13); //Keep looping until enter is pressed
    }
}

旁注:始终检查 fopen 的 return 值以查看它是否成功。 fopen returns NULL 失败。

我不知道这个 getch 函数,但我通常会做以下等待输入键的操作:

while(getchar()!='\n');

但如果您使用 scanf 时会出现问题,因为 scanf 让缓冲区中的最后一个输入被按下。

编辑:帅哥的回答更好!