-1

I read data from 2 files and stored in 2 different arrays using 2 while loop. The problem is when I want to print data in the first array or from the first while loop after the second while loop, I got the random result which was not the same as appeared in the file.

example1.txt

4.562
5.758
9.865
10.235
12.575

example2.txt

15.756
17.698
56.689
62.145
#include <stdio.h>

int main(){
    FILE *fp, *fp2;

    fp = fopen("example1.txt", "r");
    fp2 = fopen("example2.txt", "r");
    float breaks_buffer[255], yr_buffer[1000], res1[200];
    float new_data_breaks[200], new_data_yr[200];
    int i, new_index_breaks, j, new_index_yr, a;

    /*=========== GET DATA FROM FILES INTO ARRAYS  ==========*/

    /*=== DATA_BREAKS INTO ARRAY:  "new_data_breaks" ===*/
    i=0;
    new_index_breaks =0;
    while(!feof(fp)){
        fscanf(fp, "%f", &breaks_buffer[i]);
        new_data_breaks[new_index_breaks] = breaks_buffer[i];
        i++;
        new_index_breaks++;
    }
    /*=== DATA_YR INTO ARRAY:  "new_data_yr" ===*/
    j=0;
    new_index_yr =0;
    while(!feof(fp2)){
        fscanf(fp2, "%f", &yr_buffer[j]);
        new_data_yr[new_index_yr] = yr_buffer[j];
        j++;
        new_index_yr++;
    }

    /*=== TEST PRINT DATA ===*/
    for(a=0; a<new_index_breaks;a++){
        printf("%f\n",new_data_breaks[a]);
    }
    fclose(fp);
    fclose(fp2);
    return 0;
}
  • 4
    To start with - [why-is-while-feoffile-always-wrong](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong). – H.S. Jul 16 '19 at 02:51
  • After `feof` - you always need to check the result of `fopen()` – John3136 Jul 16 '19 at 02:51
  • Yes the result in the array is the same in the file if i check result after feof. but in the case I need to use the array for further maths operation, it returns the random values. – Chubby Rider Jul 16 '19 at 02:54
  • `while (i < 255 && fscanf(fp, "%f", &breaks_buffer[i]) == 1) { ... }` – David C. Rankin Jul 16 '19 at 02:55

1 Answers1

-2

try while(fscanf( ~~~) != EOF ) {...}

and are arrays for buffer really needed?? id rather not use those in my case. good luck.