Jonath P
Jonath P

Reputation: 571

Read int OR float from file in C

Let's consider a file of less than 10 numbers which can either int or float. I want to read them and add them to an array.

The issue I'm facing is that I can do that well if I have only ints for example, but it messes things up whenever it reaches a float

in file.data

11
22
33.3
44
55

my code :

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

void usage(char * message) ;


int main(int argc, char * argv[]){

    //opening the file
    FILE * flux = fopen("file.data", "r");
    if (!flux) usage("error opening the file");

    int array[10]; //array to host the data
    int i=0;
    int lu;

    while ((lu = fscanf(flux, "%i", &array[i])) !=EOF && i<10){
        printf("lu %i\n", lu );
        printf("array[%i] %i\n", i, array[i] );
        printf("\n");
        i++;
    }

    return 0 ; }

void usage(char * message) { fprintf(stderr, "%s\n", message) ; exit(1) ;}

output :

lu 1
array[0] 11

lu 1
array[1] 22

lu 1
array[2] 33

lu 0
array[3] 0

lu 0
array[4] 4196464

lu 0
array[5] 0

lu 0
array[6] 4195936

lu 0
array[7] 0

lu 0
array[8] 904651696

lu 0
array[9] 32766

How can I use fscanf so that it doesn't get bogged down when it reaches a float?

(I can tell that it doesn't seem right to declare an array of int and to try to input some float... any way around that?)

edit: my goal is to be able to read my array and print its content with their index, for example with my data :

0. 11
1. 22
2. 33.3
3. 44
4. 55

Upvotes: 1

Views: 1433

Answers (1)

Ruocco
Ruocco

Reputation: 575

Do you only need integers? If so you can read float and convert them into integers before putting them in the array:

float tmp;
while ((lu = fscanf(flux, "%f", &tmp)) !=EOF && i<10){
    array[i] = (int)tmp; //you could use some rounding here
    printf("lu %i\n", lu );
    printf("array[%i] %i\n", i, array[i] );
    printf("\n");
    i++;
}

Upvotes: 2

Related Questions