簡體   English   中英

使用fscanf()使用feof()

[英]Using fscanf() using feof()

這是我的代碼。

#include<stdio.h>
void main(){
    FILE *fp;
    int a,b;
    fp=fopen("hello.txt","r");
    while(!feof(fp)){
      fscanf(fp,"%d %d",&a,&b);
      printf("%d %d\n",a,b);
    }
}

我的hello.txt是

1   2
3   4

我的輸出是

1   2
3   4
4   4

為什么我的最后一行被打印兩次。 還沒有fp達到EOF?

此外,stackoverflow中的標記Usually, when it is used, the code using it is wrong.Usually, when it is used, the code using it is wrong. 這是什么意思?

謝謝。

如果不立即檢查結果,就不能執行輸入操作!

以下應該有效:

while (fscanf(fp,"%d %d",&a,&b) == 2)
{
    printf("%d %d\n",a,b);
}

這將在第一次轉換失敗或文件結束時停止。 或者,您可以區分轉換失敗(跳過錯誤的行)和文件結束; 請參閱fscanf的文檔。

此外,stackoverflow中的標記Usually, when it is used, the code using it is wrong.Usually, when it is used, the code using it is wrong. 這是什么意思?

這意味着使用feof()函數(以及一般的EOF的其他功能)的方式經常被誤解和錯誤。 你的代碼也是如此。

首先, fscanf()並不總能按照您的想法執行,並且使用fgets()可以更好地從文件中獲取行。 但是,如果您真的傾向於使用fscanf() ,那么檢查它是否可以讀取某些內容,否則當它不能時,您將打印變量超過需要的時間。 所以你應該做的是:

fp = fopen("hello.txt", "r");

while(fscanf(fp, "%d %d", &a, &b) == 2) {
    printf("%d %d\n", a, b);
}

fclose(fp);

另外,請使用空格,您的代碼很難閱讀。

你得到額外一行的原因是 fscanf第三次嘗試讀取之后才設置EOF,因此它失敗了,無論如何你打印結果。 這會做你想要的事情:

while(1){
  fscanf(fp,"%d %d",&a,&b);
  if (feof(fp))
     break;
  printf("%d %d\n",a,b);
}

(注意,此示例不檢查錯誤,僅針對EOF)

您可以執行以下操作:

#include <stdio.h>

void main(){
    FILE *fp;
    int a,b;
    fp=fopen("file.txt","r");
    while(fscanf(fp,"%d %d",&a,&b)==2)
    {
      printf("%d %d\n",a,b);
    }
}

暫無
暫無

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

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