0

I'm trying to create 4 arrays with a text file. The text file look like this :

1000 Docteur             Albert              65.5
1001 Solo                Hanz                23.4
1002 Caillou             Frederic            78.7
…

The code:

void creer (int num[], char pre[][TAILLE_NP+1], char nom[][TAILLE_NP+1], 
float note[], int * nb ){

  int  n = 0, i; /*nb personnes*/

  FILE *donnees = fopen("notes.txt", "r");

  if(!donnees){
    printf("Erreur ouverture de fichier\n");
    exit(0);
  }

  while (!feof(donnees)){

    fscanf(donnees,"%d", &num [n]);
    fgets(nom[n], TAILLE_NP+1, donnees);
    fgets(pre[n], TAILLE_NP+1, donnees);
    fscanf(donnees,"%f\n", &note[n]);

    printf("%d %s %s %f\n",num[n], nom[n], pre[n], note[n]);
    n++;
    }

  fclose (donnees);

  *nb = n ;
  }


int main() {

  int num[MAX_NUM];
  int nbEle;

  char pre[MAX_NUM][TAILLE_NP+1],
       nom[MAX_NUM][TAILLE_NP+1];

  float note[MAX_NUM];

  creer (num, pre, nom, note, &nbEle);

  printf("%s", pre[2]); //test

  return 0; 
}

The problem is, I'm sure there is a better way to create the arrays, im a beginner. Also, there is a problem with the float, the decimal aren't right when I printf. For example, 78.7 become 78.699997. What am I doing wrong? Thanks ! :)

alk
  • 69,737
  • 10
  • 105
  • 255

2 Answers2

1

Two issues here:

  1. Mixing fscanf() and fgets() is a bad idea, as the former works on parts of a line and latter on a complete line.

  2. float isn't as precise as you might expect it to be.


To solve 1:

fscanf(donnees, "%d", &num[n]);
fscanf(donnees, "%s", nom[n]);
fscanf(donnees, "%s", pre[n]);
fscanf(donnees, "%f\n", &note[n]);

To avoid overflowing the "strings" you can tell fscanf() how much to scan in as a maximum by using, for example, "%42s" for a string of 42 chars (not counting the 0-terminating char).


To solve 2:

Make note be doubles and do

fscanf(donnees,"%lf\n", &note[n]);
alk
  • 69,737
  • 10
  • 105
  • 255
0

Several issues here:

Floating point is very tricky. Read floating-point-gui.de (and remember that URL).

Don't allocate huge automatic variables on your call stack. A typical call frame should have no more than few kilobytes (and your entire call stack should be less than one or a few megabytes). Use C dynamic memory allocation.

C has only one-dimensional arrays. If you need better, make some abstract data type (generally, avoid arrays of arrays). Look at this for inspiration.

Read carefully the documentation of every standard function. You should test the result of fscanf.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547