Hi all, my code seems to work, the only problem is that the sscanf function makes me a double copy of a value. I'm sure the problem is the sscanf function because I tried to print the vector filled by the fgets function and print the file correctly.
Code:
#include <stdio.h>#include <string.h>
#include <stdlib.h>
#define N 100
struct INFORMAZIONE{
int eta_informazione;
int prezzo_informazione;
struct INFORMAZIONE *next;
};
typedef struct INFORMAZIONE informazione;
void Genera_Lista(FILE *ptr_paganti);
int main (){
FILE *ptr_paganti;
ptr_paganti = fopen("Utenti_PAGANTI.txt" , "r");
Genera_Lista(ptr_paganti);
return 0;
}
void Genera_Lista(FILE *ptr_paganti){
int somma = 0;
int eta_media = 0;
int num_visitatori = 0;
char utenti_line[N];
informazione *head, *current;
head = current = NULL;
if (ptr_paganti == NULL){
printf("Errore, file non trovato!");
}
else {
while(fgets(utenti_line,sizeof(utenti_line),ptr_paganti)!= NULL){
char cognome_temp[N];
char nome_temp[N];
int eta_temp;
int biglietto_temp;
printf("%s\n" , utenti_line);
sscanf(utenti_line, "%s %s %d %d", cognome_temp, nome_temp, &eta_temp, &biglietto_temp);
informazione *node = malloc(sizeof(informazione));
node-> eta_informazione = eta_temp;
node-> prezzo_informazione = biglietto_temp;
node->next = NULL;
if(head == NULL){
current = head = node;
}
else {
current = current->next = node;
}
num_visitatori = num_visitatori +1;
}
fclose(ptr_paganti);
}
printf("\n\n");
printf("\nLINKED LIST\n");
for(current = head; current ; current=current->next){
printf("(%d," , current->eta_informazione);
printf("%d)-> " , current->prezzo_informazione);
somma = somma + current->eta_informazione;
eta_media = somma/num_visitatori;
}
printf("NULL\n");
printf("\n\n");
printf("Il numero di visitatori del cinema e' : %d\n" , num_visitatori);
printf("L'eta' media dei clienti e' : %d" , eta_media);
}
This is the output and how you can see in the second node there is a copy of the first.