School-Coding-Cpp/sfusi/es22_scrivitab_foschini_fil...

88 lines
2.2 KiB
C++

/*
Nome: Mario
Cognome: Montanari
Classe: 3IAN
Data: 09/04/2025
es22. (scrivitab)
Scrivere un programma che legga da tastiera e memorizzi in
un'apposita struttura dati la seguente tabella:
+-----------------+-----------------+-------------+-------------+
| Cognome | Nome | Altezza (m) | Peso (kg) |
+-----------------+-----------------+-------------+-------------+
| Rossi | Mario | 1.75 | 76 |
| Ferraro | Carlo | 1.84 | 82 |
| Marelli | Chiara | 1.65 | 58 |
+-----------------+-----------------+-------------+-------------+
Terminato il caricamento, il programma deve memorizzare l'intera
tabella nel file di testo tabella.txt (un record per linea, campi
separati con un tabulatore; non deve essere memorizzata la riga
d'intestazione). Si ipotizzi che tutti i campi testuali siano
privi di spazi, che le altezze siano numeri float e i pesi numeri
interi.
NOTA BENE: usare la funzione strncpy()
*/
#include <iostream>
#define SIZE 100+1
#define SIZE_LINE 1000+1
using namespace std;
typedef struct {
char nome[SIZE];
char cognome[SIZE];
float altezza;
int peso;
} anagrafe;
void apriFile(const char * nomeFileSorgente, const char * nomeFileDestinazione);
int main(void) {
apriFile("tabella.txt", "testo.txt");
return 0;
}
void apriFile(const char * nomeFileSorgente, const char * nomeFileDestinazione) {
FILE * fr = fopen(nomeFileSorgente, "rt");
if (fr != NULL) {
FILE * fw = fopen(nomeFileDestinazione, "wt");
if (fw != NULL) {
char riga[SIZE_LINE];
anagrafe caratteristica;
for (int i = 0; i < 3; i++) {
fgets(riga, sizeof(riga), fr);
}
while (fscanf(fr, "| %16s | %16s | %f | %d | %*[\n]",
caratteristica.cognome,
caratteristica.nome,
&caratteristica.altezza,
&caratteristica.peso
) == 4) {
fprintf(fw, "%s\t%s\t%.2f\t%d\n",
caratteristica.cognome,
caratteristica.nome,
caratteristica.altezza,
caratteristica.peso
);
}
fclose(fw);
} else {
perror("Error (destination)");
}
fclose(fr);
} else {
perror("Error (source)");
}
}