簡體   English   中英

我的 fgetc 沒有返回所需的 output。 (C編程初學者)

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

我在運行代碼之前創建的 My.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//

我想要的這個程序的output和上面一樣,代碼如下:

#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;

output 如下:

 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 循環),但 output 仍然出現故障。 我已經閱讀了一些存檔的 Macbook Pro 文檔,這些循環正在讀取來自輸入 stream 的推回輸入,並且它似乎也一直在為我的代碼執行此操作(或者我可能錯了)。

有人可以告訴我我編寫的代碼有什么問題以及為什么我的計算機沒有按我的意願輸出 .txt 文件嗎?

我目前在 VSCode 上運行 Cygwin GCC。

我的系統是 2019 年的 Macbook Pro 16

您每打印一個字符就讀取 2 個字符。 第一個字符由“buck=fgetc(filepointer)”作為 while 語句中的參數讀取。 第二個字符由 "printf("%c",fgetc(filepointer));" 讀取。

所以基本上你的程序首先從文件中讀取一個字符並將其存儲在“buck”中,然后讀取另一個字符並將其打印出來,導致 output 缺少字符。

你可以這樣做:

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

為每次掃描簡單地打印降壓。 祝你好運!

@SSORshen 說的是正確的,但是你在for循環中也有類似的問題,在rewind之后。 但是在這里你每次迭代調用fgetc三次,所以你只打印每三個字符。 另請注意, buck包含讀取的字符,而不是計數。 如果要計算讀取了多少個字符,則需要使用單獨的計數器變量,例如下面的i 您的第二個循環應該看起來更像這樣:

counter=1;
rewind(filepointer);

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM