我的 fgetc 没有返回所需的输出。 (C编程初学者)

My fgetc is not returning a desired output. (C programming beginner)

我在 运行 代码之前创建的 .txt 文件如下所示:

/*
I am Jason and I love horses hahaha/n
 This is amazing, How much I love horses, I think I am in love/n
 how many people love horses like I do?/n/n
this is quite a horsed up paragraph
*/ 

//I also manually wrote '[=10=]' character at the end of my string//

我想要的这个程序的输出与上面相同,代码如下:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int main()

{

    FILE *filepointer;

    int buck;

    int counter=1 ;

    filepointer = fopen("inoutproj.txt","r");
    
    while(buck=fgetc(filepointer),buck!=EOF)
    {
        if(buck=='\n')
        {
            ++counter;
        }
        printf("%c",fgetc(filepointer));
    }
    printf("\nThere are %d lines in the text file\n\n",counter);

    counter=1;
    rewind(filepointer);

    for(buck=fgetc(filepointer);buck<175;++buck)
    {
        if(fgetc(filepointer)=='\n')
        {
            ++counter;
        }
        printf("%c",fgetc(filepointer));
    }

    printf("\nThere are %d lines in the text file\n",counter);
    fclose(filepointer);
    return 0;

输出如下:

 mJsnadIlv osshhh

Ti saaig o uhIlv oss  hn  mi oe o aypol oehre ieId?

hsi ut  osdu aarp�

There are 3 lines in the text file


a ao n  oehre aaa hsi mzn,Hwmc  oehre,ItikIa nlv

hwmn epelv osslk  o

ti sqieahre pprgah���������������

文本文件中有3行


如您所见,我使用 fgetc 尝试了两种不同的方法(While 循环和 for 循环),但输出仍然出现问题。我已经阅读了一些存档的 Macbook Pro 文档,其中循环正在从输入流中读取推回的输入,并且它似乎也一直在为我的代码执行此操作(或者我错了)。

谁能告诉我我编写的代码有什么问题以及为什么我的计算机没有按我的意愿输出 .txt 文件?

我目前 运行 Cygwin GCC VSCode。

我的系统是 Macbook Pro 16in 2019

您每打印一个字符,就会阅读 2 个字符。第一个字符被“buck=fgetc(filepointer)”读取为 while 语句中的参数。第二个字符被 "printf("%c",fgetc(filepointer)); 读取。

所以基本上你的程序首先从文件中读取一个字符并将其存储在“buck”中,然后读取另一个字符并打印出来,导致输出丢失字符。

你可以这样做:

FILE *filepointer;

int buck;

int counter=1 ;

filepointer = fopen("inoutproj.txt","r");

while(buck=fgetc(filepointer),buck!=EOF)
{
    if(buck=='\n')
    {
        ++counter;
    }
    printf("%c",buck);
}
printf("\nThere are %d lines in the text file\n\n",counter);

为每次扫描简单地打印 buck。 祝你好运!

@SSORshen 说的是对的,但是在 rewind 之后的 for 循环中也有类似的问题。但是在这里你每次迭代调用 fgetc three 次,所以你只打印每个 third 个字符。另请注意 buck 包含读取的字符,而不是计数。如果您想计算读取了多少个字符,则需要使用单独的计数器变量,例如下面的 i。你的第二个循环应该看起来更像这样:

counter=1;
rewind(filepointer);

for(int i=0;i<175;++i)
{
    buck=fgetc(filepointer);
    if(buck=='\n')
    {
        ++counter;
    }
    printf("%c",buck);
}