簡體   English   中英

C從一個文件讀取數據並將計算結果存儲在另一個文件中

[英]C read data from one file and store calculations in another file

我是C語言的初學者。 在這里,我想從文件* fileptrIn中讀取數據並進行一些計算,並將答案存儲在* fileptrOut中。 但是我在文件* fileptrIn中的第一個元素上遇到了無限循環。 在終端中,它僅重復打印文件* fileptrIn中的第一個元素。 由於沒有任何編譯錯誤,因此無法檢測到該錯誤。 有任何編輯我的代碼的建議嗎?

#include<stdio.h>

int main(void)
{
int value;
int total = 0;
int count = 0;

FILE *fileptrIn;

fileptrIn = fopen("input.txt", "r");

if(fileptrIn == NULL)
{
    printf("\nError opening for reading.\n");

    return -1;
}

printf("\nThe data:\n");

fscanf(fileptrIn, "%d", &value);

while(!feof(fileptrIn))
{
    printf("%d", value);

    total += value;

    ++count;
}

fclose(fileptrIn);

return 0;
}
while(!feof(fileptrIn))
{
    printf("%d", value);

    total += value;

    ++count;
}

您沒有在循環內讀取任何內容,因此文件指針不會前進到EOF

除了其他答案,並繼續我的評論,您需要驗證所有輸入。 您可以在消除while (!feof(file))問題的while (!feof(file))完成此操作,如下所示:

while (fscanf (fileptrIn, "%d", &value) == 1) {
    printf ("%d", value);
    total += value;
    ++count;
}

暫無
暫無

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

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