-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?
In this passage:
while(fscanf(f, "%d", &v[N]) == 1)
 {
 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)
 {
 printf("%d\n", v[N]);
 N++;
 }
.– anonimo