Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * C++ Program to Count lines in a file
- */
- #include<iostream>
- #include<fstream>
- using namespace std;
- /**
- * Legge il file avente nome filename carattere per carattere.
- * Al ritorno
- * - chars contiene il numero di caratteri letto
- * - words contiene il numero delle parole lette (separate da spaci o ritoni a capo)
- * - lines contiene il numero delle righe (non vuote) lette
- *
- * Ritorna 0 se c'e' stato qualche errore nell'apertura del file, 1 altrimenti
- */
- int we(const char *filename, int *chars, int *words, int *lines) {
- // Creiamo l'input stream
- ifstream inFile;
- // Cerca di aprire il file
- inFile.open(filename);
- // Se c'e' qualche errore, ritorna 0
- if (!inFile) {
- return 0;
- }
- // Inizializzazione dei valori, per essere sicuri di partire da 0
- // Essendo chars, words e lines passati per riferimento, non possiamo
- // sapere che valori iniziali avranno
- int charCount = 0;
- int wordsCount = 0;
- int lineCount = 0;
- string line;
- // Scorri ogni riga
- while (getline(inFile, line)) {
- int lineCharCount = 0;
- bool previousIsChar = false;
- for (int i = 0; i < line.length(); i++) {
- // Sto leggendo un carattere in ogni caso
- lineCharCount += 1;
- // Controllo se ho trovato uno spazio o un terminatore di riga
- if (line[i] == ' ' || line[i] == '\n' || line[i] == '\r') {
- // Se il carattere precedente allo spazio o al terminatore era diverso
- // da un terminatore, allora vuol dire che ho appena finito una parola
- if (previousIsChar) {
- wordsCount += 1;
- previousIsChar = false;
- }
- } else {
- if (!previousIsChar && i == line.length() - 1) {
- wordsCount += 1;
- }
- previousIsChar = true;
- }
- }
- if (lineCharCount > 0) {
- lineCount += 1;
- charCount += lineCharCount;
- }
- }
- // Chiudiamo l'input
- inFile.close();
- // Copiamo i valori
- *chars = charCount;
- *words = wordsCount;
- *lines = lineCount;
- return 1;
- }
- int main(int argc, char *argv[]){
- int charCount = 0;
- int wordsCount = 0;
- int lineCount = 0;
- we(argv[1], &charCount, &wordsCount, &lineCount);
- cout << "Number of lines in the file: " << lineCount << endl;
- cout << "Number of words in fhe file: " << wordsCount << endl;
- cout << "Number of chars in fhe file: " << charCount << endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment