简体   繁体   中英

Reading from file into array and performing operations with numbers in the array

Hi i need to read numbers from file and make a new file with only repeated numbers included.
I run into problem that when i read into array those numbers are not seperated.

So I want to ask how to read numbers from files with spaces or how to know when number ends?

Because if I read like this i can't do any more operations with those numbers.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
  FILE *file = fopen("w.txt", "r");
  int integers[100];

  int i = 0;
  int num;
  while (fscanf(file, "%d", &num) > 0)
  {
    integers[i] = num;
    i++;
    printf("%d", integers[i]);
  }
  fclose(file);
  system("pause");
  return 0;
}

I'd increase the index counter after having tried to print the number just read in:

while(fscanf(file, "%d", &num) > 0) {
  integers[i] = num;
  printf("%d\n", integers[i]); /* Printing a \n after each number puts it on a new line. */
  i++;

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