I have a "Temp.dat" with 200 lines that looks like this:
0.060493 1 0.5 1
1.596961 0 0.1 2
0.87758 1 0.3 1.5
0.165453 1 0 3
0.07085 1 0.3 4
0.125379 1 0.2 3
0.454202 1 0.2 2
0.373227 1 0.3 1
0.131486 1 0.3 3
0.867477 0 0.5 4
0.122609 0 0.8 9
I am trying to read each line and store each column of data into separate arrays with the following code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 200
int main(){
double x[MAX], y[MAX];
double a, b;
int m = 0;
FILE* file;
file = fopen("Temp.dat", "r");
if ( file != NULL ){
/* Read the two columns. */
while(fscanf(file, "%d %d", &a, &b) == 2)
{ x[m] = a;
y[m] = b;
m++;
}
}
printf("%d %d\n", x[4], y[1]); # Test the stored inputs of the two arrays
return(0);
}
When I tried printing out the result, it gave 1 13258992, rather than 0.165453 0. I cannot understand where it got the pair 1 13258992, as I thought the line fscanf(file, "%d %d", &a, &b) == 2 did what it's supposed to do: go through each row of the file Temp.dat and read the two double-type integers, then stored in the two arrays x[MAX] and `y[MAX]. Therefore, could anyone please help me fix this issue?
Another question: After storing the two columns above in two arrays x[MAX] and y[MAX], I would like to sort the two arrays in an increasing order based on the values in the first array x[MAX]. This would look like:
0.060493 1
0.07085 1
0.122609 0
0.125379 1
0.131486 1
0.165453 1
0.373227 1
0.454202 1
0.867477 0
How could I do this sorting routine in C, as it's quite hard to arrange the elements in y[MAX] to follow the order of their corresponding elements in x[MAX]?
while, and change%dto%lf, but the result is still incorrect. Now it gave me-1 34902256for the samex[4] y[1]. Could you give me some hints on how to sort the second array while I am swapping each element of the first array?printfcall. See my answer.