0

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
jabroni
  • 97
  • 8
  • Classic mistake. [Never use fscanf](https://stackoverflow.com/questions/58403537/what-can-i-use-for-input-conversion-instead-of-scanf). – zwol Nov 19 '20 at 03:17
  • @zwol Hmmm link is to troubles with `scanf()`, not `fscanf()`. Similar - yet different enough to not warrant the _never_. – chux - Reinstate Monica Nov 19 '20 at 12:39
  • @chux-ReinstateMonica *All* of the scanf family of functions are broken as specified and should never be used. Using them to read standard input is especially troublesome and also especially common for beginners, so that's what the linked discussion focuses on, but OP's code has undefined behavior on malformed input just the same. – zwol Nov 19 '20 at 13:15

1 Answers1

4
    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 ints 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);
}
David Schwartz
  • 166,415
  • 16
  • 184
  • 259