Hamza Hamza - 4 months ago 8
C Question

I need to read x and y values from .txt file in C

I need to read x and y coordinates from a text file then use them for polynomial regression. I can do the regression part but I can't read the values from the file. Data points are

5,10,15,20,25,30,35,40,45,50

17,24,31,33,37,37,40,40,42,41

First row is x and second row is y, and they're exactly written like this in the txt file.

From another question I managed to read all the numbers into a single x array of 20 but I really need for them in seperate arrays as x and y. How can I do this?
Here's my current code:

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

int main()
{
FILE *data;
data = fopen("data.txt", "r");

int x[20];
int i=0;


for(i=0; i<20; i++)
fscanf(data, "%d,", &x[i]);


for(i=0; i<20; i++)
printf("x are: %d\n", x[i]);


fclose(data);
return 0;
}


Thanks in advance.

sps sps
Answer

If you always have 10 int in one line and 10 more int in another line as you stated in your question, you can use one more array int y[10]; to store y values. And use two for loops - one for reading 10 x values, and another for reading 10 y values. And both your arrays just need to store only 10 elements.

    int x[10];
    int y[10];  // Array to store y values
    int i=0;

    for(i=0; i<10; i++) // Read first 10 values to x array
            fscanf(data, "%d,", &x[i]);

    for(i=0; i<10; i++) // Read next 10 values to y array
            fscanf(data, "%d,", &y[i]);

    for(i=0; i<10; i++)
            printf("x are: %d\n", x[i]);

    for(i=0; i<10; i++)
            printf("y are: %d\n", y[i]);

However if there is a chance that there may be different number of integers - more or less than 10 - in those lines then you will need to do more checks.