1

I'm trying to write code that reads couple of numbers from FILE in the form of x y and stores them in two arrays, and i want the function to returns the number of couples, i tried with a FILE that contains 5 couples, but it seems that FILE *ptr goes beyond and reaches the sixth lines, here is my code:

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

int main()
{  
   int X[100],Y[100];
   int i=0; int Ncouple = 0 ;int M = 5;

   FILE *fptr;
   fptr = fopen("num.data", "r");
   
   if( fptr == NULL)
   {
    printf("fail");
    exit(1);
   }
   
   while(!feof(fptr))
   {
     fscanf(fptr,"%d %d",&X[i],&Y[i]);
     printf("\nX[%d] = %d Y[%d] = %d\n",i,X[i],i,Y[i]);
     i++;Ncouple++;
   }

   fclose(fptr);
   return 0;
}

When i execute i get X[6] and Y[6] but my date file contains only 5 lines. Where am i wrong ?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

1 Answers1

3

The condition in the while statement is the reason of the behavior that you described.

while(!feof(fptr))

This condition will be equal to true after you will try already to read a non-existent record in the file.

Rewrite the while loop like

while( fscanf(fptr,"%d %d",&X[i],&Y[i]) == 2 )
{
    printf("\nX[%d] = %d Y[%d] = %d\n",i,X[i],i,Y[i]);
    i++;Ncouple++;
}

Pay attention to that instead of this line of declarations

int i=0; int Ncouple = 0 ;int M = 5;

it would be better to write

int i=0; 
int Ncouple = 0;
int M = 5;

Or at least like

int i=0, Ncouple = 0, M = 5;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thank you, i wasted too many time on this problem, but i want to know why this work and why 2 ? –  Sep 29 '20 at 18:20
  • @ElMehdiAKKOUCHE The function fscanf in the case of success returns the number of input items assigned,. – Vlad from Moscow Sep 29 '20 at 18:21
  • @ElMehdiAKKOUCHE As there are no more answers you can select my answer as the best to close your question. – Vlad from Moscow Sep 29 '20 at 18:25
  • Sorry can you explain with a different manner i dont understand –  Sep 29 '20 at 18:32
  • @ElMehdiAKKOUCHE If a call of fscanf is successful then it means that the both items C[i] and Y{i] got values. There are two items and they both got values. So the function returns 2 in the case of success. In a case of an error it returns EOF. – Vlad from Moscow Sep 29 '20 at 18:35
  • Thanks a lot, hope to learn more from you –  Sep 29 '20 at 18:40