0

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

如果没有以下行,我的代码将显示整个文本文件。if (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 );
}
4

2 回答 2

1

你想要 scanf("%d", &y) 而不是 scanf("&d", &y)。

于 2012-08-16T01:30:42.427 回答
0

你想要scanf("%d", &y)而不是scanf("&d", &y).

你也从不初始化lineCount,所以它的初始值不保证为 0。

于 2012-08-16T01:32:56.263 回答