I am trying read numbers from a text file and store it into an array. When I try to read the numbers that are in the array, the output is slighty off. This is my code:
struct point{
double x[7];
double y[7];
}point;
int main()
{
FILE *fp;
fp = fopen("data_2.txt", "r");
struct point points;
int len = 8;
int i = 0;
int j = 0;
int k = 0;
double a = 0;
double b = 0;
double c = 0;
double total = 0;
int left=0;
int right=0;
int line = 0;
for (i=0;i<len;i++)
{
fscanf(fp, "%lf %lf", &points.x[i],&points.y[i]);
}
for(i = 0; i < len;i++)
printf("looking at point %.2f %.2f\n",points.x[i],points.y[i]);
return(0);
}
the Test file I use contains the following digits
2.3 7.5
7.6 7.1
8.5 3.0
5.9 0.7
1.0 2.0
5.1 5.8
4.0 4.5
4.3 3.4
The output I get is this:
looking at point 2.30 4.30
looking at point 7.60 7.10
looking at point 8.50 3.00
looking at point 5.90 0.70
looking at point 1.00 2.00
looking at point 5.10 5.80
looking at point 4.00 4.50
looking at point 4.30 3.40
What is it that I am doing wrong?
The problem is your struct isn't big enough to store 8 numbers and it's invoking undefined behavior. You have double x[7]
but you're looping to 8.
Why you're getting that specific behavior, and I can reproduce it here on OS X, I'm not sure. But that's undefined behavior for you.
Update your struct like this:
struct point{
double x[8];
double y[8];
}point;
This will help you read and display the data correctly. example-with-stdin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With