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

问题描述

我在运行代码之前创建的 .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 '\0' 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 文件

我目前正在 VSCode 上运行 Cygwin GCC。

我的系统是 Macbook Pro 16in 2019

解决方法

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

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

你可以这样做:

for

只需为每次扫描打印 buck。 祝你好运!

,

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

counter=1;
rewind(filepointer);

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