简体   繁体   中英

Reading and outputting integers from a file in C

I created a file with content: '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'

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 returns the number of input items successfully matched and assigned.In your case, fscanf returns 1 on successful scanning. So just read integers from the file until fscanf returns 0 like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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