I am trying to store a series of values from a configuration file which have data types of int
and float
. I'm not sure why, but when I print the values inside the array, the int value returns a large number, and the floats return NAN.
Configuration file:
1666 -0.314913523 0.999804843
1667 -0.337279687 0.999865966
1703 -0.323162231 0.999774194
1704 -0.311984064 0.99964375
1705 -0.311984064 0.99964375
1706 -0.313381260 0.999671436
1707 -0.313170802 0.999558174
My code:
#include <iostream>
using namespace std;
#define NUM_ITEMS 50
int main()
{
FILE *fp;
fp = fopen("config.conf","r");
int a[NUM_ITEMS][NUM_ITEMS];
float b[NUM_ITEMS][NUM_ITEMS];
float c[NUM_ITEMS][NUM_ITEMS];
int i = 0;
while(fscanf(fp,"%i\t%f\t%f", a[i], b[i], c[i]) != EOF)
{
printf("%i %f %f\n", a[i], b[i], c[i]);
i++;
}
fclose(fp);
}
output:
1149516976 -nan 0.000000
1149517176 -nan 0.000000
1149517376 -nan 0.000000
1149517576 -nan 0.000000
1149517776 -nan 0.000000
1149517976 -nan 0.000000
1149518176 -nan 0.000000
int a[NUM_ITEMS][NUM_ITEMS];
float b[NUM_ITEMS][NUM_ITEMS];
float c[NUM_ITEMS][NUM_ITEMS];
This makes a
, b
, and c
arrays of arrays, so a[i]
is an array. You want:
int a[NUM_ITEMS];
float b[NUM_ITEMS];
float c[NUM_ITEMS];
So that a
is an array of int
s and now a[i]
is an int
. You need to pass the address to scanf
though.
Here's the code with all major issues fixed:
#include <iostream>
#define NUM_ITEMS 50
int main()
{
FILE *fp;
fp = fopen("config.conf","r");
if (fp == NULL)
return -1;
int a[NUM_ITEMS];
float b[NUM_ITEMS];
float c[NUM_ITEMS];
int i = 0;
while(fscanf(fp,"%i\t%f\t%f", &a[i], &b[i], &c[i]) == 3)
{
printf("%i %f %f\n", a[i], b[i], c[i]);
i++;
}
fclose(fp);
}