【问题标题】:My fgetc is not returning a desired output. (C programming beginner)我的 fgetc 没有返回所需的输出。 (C编程初学者)
【发布时间】:2021-07-22 18:06:00
【问题描述】:

我在运行代码之前创建的 .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。

我的系统是 2019 年的 Macbook Pro 16

【问题讨论】:

  • '\0' 字符最后通过 fputs 使用另一个程序写为 \0。
  • 数字 175 也来自运行 fseek 和 ftell。为了弄清楚如何使用 for 循环,我决定运行: fseek(filepointer,0,SEEK_END); printf("%ld",ftell(filepointer));找出我的文件末尾的数值。我不确定这个数字是否是我想要的。

标签: c fgetc


【解决方案1】:

您每打印一个字符就读取 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。 祝你好运!

【讨论】:

  • 在那次降压之后,我的循环似乎永远持续下去!='!'。我尝试了降压!=EOF,它奏效了!感谢 printf 的提示!太棒了!
【解决方案2】:

@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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-20
    • 2013-06-28
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多