Save values from a text file to an array

Asked

Viewed 128 times

-1

I’m trying to make a code where I need to store numbers from a text file in an array. The code I have is this::

#include <stdio.h>

int main()
{
  FILE *f;
  int v[10];
  int N=0;
  f=fopen("numeros.txt", "r");
  if(f==NULL)
  {
    printf("Não foi possivel abrir o ficheiro.\n");
    return 0;
  }
  while(fscanf(f, "%d", &v[N]) == 1)
  {
    fscanf(f, "%d", &v[N]);
    printf("%d\n", v[N]);
    N++;
  }
  fclose(f);
  return 0;
}

The.txt number file contains:

1
2
3
4
5
6
7
8

The problem is that when meto fscanf(f, "%d", &v[N]) == 1 or fscanf(f, "%d", &v[N]) != EOF inside the while, only the numbers 2, 4, 6, 8 appear on the screen.

I managed to achieve the result I wanted using ! feof(f) inside the while and it worked perfectly, but I wonder why using the fscanf method the code didn’t work properly.

I have also seen in some places that it is not correct to use only feof(f) to test the end of the text file, someone can explain to me why?

  • 2

    In this passage: while(fscanf(f, "%d", &v[N]) == 1)&#xA; {&#xA; fscanf(f, "%d", &v[N]); you make two consecutive fscanf by playing the reading result on the same variable. Delete this internal fscanf from the loop. Just leave it: while(fscanf(f, "%d", &v[N]) == 1)&#xA; {&#xA; printf("%d\n", v[N]);&#xA; N++;&#xA; }.

1 answer

1


#include <stdio.h>

int main()
{
  FILE *f;
  int v[10];
  int N=0;
  f=fopen("numeros.txt", "r");
  if(f==NULL)
  {
    printf("Não foi possivel abrir o ficheiro.\n");
    return 0;
  }
  while(fscanf(f, "%d", &v[N]) == 1)
  {
    printf("%d\n", v[N]);
    N++;
  }
  fclose(f);
  return 0;
}

Note that when you enter the fscanf() command within the while condition, it is executed and not only checked if it is possible to execute it, and since the same command appears inside the loop what you have done is to read twice and therefore add two by two the values of the file in its array, just remove the fscanf() command from inside the while block, after all it has already run when the while tests your condition and your problem is solved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.