【问题标题】:Reading and outputting integers from a file in C从 C 文件中读取和输出整数
【发布时间】:2014-11-08 09:30:14
【问题描述】:

我创建了一个文件,内容为:'12 7 -14 3 -8 10'

我想输出所有整数类型的数字。但是编译运行程序后,我只得到第一个数字'12'

这是我的代码:

#include <stdio.h>

main(){
    FILE *f;
    int x;
    f=fopen("C:\\Users\\emachines\\Desktop\\ind\\in.txt", "r");
    fscanf(f, "%d", &x);
    printf("Numbers: %d", x);
    fclose(f);
}

我做错了什么?

【问题讨论】:

    标签: c file output scanf


    【解决方案1】:

    您使用fscanf从文件中扫描一个整数并打印它。您需要一个循环来获取所有整数。fscanf返回成功匹配和分配的输入项的数量。在您的情况,fscanf 在成功扫描时返回 1。因此,只需从文件中读取整数,直到 fscanf 返回 0,如下所示:

    #include <stdio.h>
    
    int main() // Use int main
    {
      FILE *f;
      int x;
    
      f=fopen("C:\\Users\\emachines\\Desktop\\ind\\in.txt", "r");
    
      if(f==NULL)  //If file failed to open
      {
          printf("Opening the file failed.Exiting...");
          return -1;
      }
    
      printf("Numbers are:");
      while(fscanf(f, "%d", &x)==1)
      printf("%d ", x);
    
      fclose(f);
      return(0); //main returns int
    }
    

    【讨论】:

    • 谢谢!你用了while(fscanf(f, "%d", &amp;x)==1),所以我想问一下。 while(fscanf(f, "%d", &amp;x)==1) 是否等同于while(!feof(f))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2014-06-09
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多