School-Coding-Cpp/sfusi/es04_contaparole_foschini_f...

82 lines
1.6 KiB
C++

/*
Nome: Mario
Cognome: Montanari
Classe: 3AIN
Data: 04/04/2025
es04. (contaparole)
Un file di testo contiene un certo numero di parole.
Ogni parola (a eccezione dell'ultima) e` separata da
quella successiva da un solo carattere di whitespace.
Scrivere un programma che, richiesta l'immissione da
tastiera del nome del file da elaborare, visualizzi il
conteggio delle parole contenute (suggerimento: contare
i whitespace...).
*/
#include <iostream>
#define SIZE_LINE 1000+1
using namespace std;
void apriFile(const char * nomeFile);
int numeroParoleFile(const char * nomeFile);
int main(void) {
char nomeFile[SIZE_LINE];
cout << "Immetti il nome del file da aprire: ";
cin >> nomeFile;
cout << endl;
apriFile(nomeFile);
cout << endl;
cout << "Numero di parole: " << numeroParoleFile(nomeFile) << endl;
return 0;
}
void apriFile(const char * nomeFile) {
FILE * fp = fopen(nomeFile, "rt");
if (fp != NULL) {
char str[SIZE_LINE];
while (fgets(str, sizeof(str), fp) != NULL) {
cout << str;
}
cout << endl;
fclose(fp);
} else {
perror("Error");
}
}
int numeroParoleFile(const char * nomeFile) {
int countWord = 0;
FILE * fp = fopen(nomeFile, "rt");
if (fp != NULL) {
char str[SIZE_LINE];
while (fgets(str, sizeof(str), fp) != NULL) {
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] != ' ') {
if (str[i + 1] == ' ' || i == strlen(str) - 1) {
countWord++;
}
}
}
}
fclose(fp);
} else {
return -1;
}
return countWord;
}