gpt4 book ai didi

c - 文件读取和字符计数

转载 作者:行者123 更新时间:2023-11-30 15:55:35 25 4
gpt4 key购买 nike

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

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

当计算的换行符数量等于用户输入的数量时,该行应该中断循环。

我可以计算 newLine 字符的数量并显示它,但是当我尝试在达到一定数量的 newLine 后打破循环时,代码会在 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)。

关于c - 文件读取和字符计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11979474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com