我正在尝试读取文件,然后按字符输出文件。我希望用户输入一个数字,该数字将是要显示的行数。

如果没有以下行,我的代码将显示整个文本文件。
如果(y == lineCount)中断;

当计数的换行符数量等于用户输入的数量时,此行应该打破循环。

我可以计算newLine字符的数量并显示出来,但是当我尝试达到一定数量的newLines后中断循环时,代码将在1个字符后中断

#include <stdio.h>

int main ( int argc, char *argv[] )
{
    FILE *file = fopen( argv[1], "r" );
    int lineCount, x, y;

    printf("enter a number of lines of lines to be displayed\n");
    scanf("&d", &y);


    while  ( ( x = fgetc( file )) != EOF )  //read characters
    {
        printf( "%c", x );       //print character

        if (x == '\n')           //check for newline character
            lineCount++;

        if (y == lineCount)      //check for newLine character
            break;               //??? y = lineCount after 1 character???
    }

    printf( "%d lines in the text file\n", lineCount );  //testing the newline characters was being read

   fclose( file );
}

最佳答案

您要用scanf(“%d”,&y)而不是scanf(“&d”,&y)。

09-03 22:56