简体   繁体   English

从C中的文件读取和输出整数

[英]Reading and outputting integers from a file in C

I created a file with content: '12 7 -14 3 -8 10' 我创建了一个包含以下内容的文件:'12 7 -14 3 -8 10'

I want to output all numbers of type integer. 我想输出整数类型的所有数字。 But after compiling and running the program, I get only the first number '12' 但是在编译并运行程序之后,我只得到第一个数字“ 12”

Here's my code: 这是我的代码:

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

What am I doing wrong? 我究竟做错了什么?

You scan one integer from the file using fscanf and print it.You need a loop to get all the integers. 您可以使用fscanf从文件中扫描一个整数并进行打印。您需要循环才能获取所有整数。 fscanf returns the number of input items successfully matched and assigned.In your case, fscanf returns 1 on successful scanning. fscanf返回成功匹配和分配的输入项目数。在您的情况下, fscanf在成功扫描时返回1。 So just read integers from the file until fscanf returns 0 like this: 因此,只需从文件读取整数,直到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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM