School-Coding-Cpp/sfusi/countWord_textfile.cpp

42 lines
719 B
C++

#include <iostream>
#include <cstring>
#define SIZE_LINE 1000+1
using namespace std;
int countWord(const char * str);
int main(void) {
FILE * file = fopen("parole.txt", "rt");
if (file != NULL) {
char str[SIZE_LINE];
int countWrd = 0;
while (fgets(str, sizeof(str), file)) {
countWrd = countWrd + countWord(str);
}
cout << "Total words: " << countWrd << endl;
fclose(file);
} else {
perror("Error (source)");
}
return 0;
}
int countWord(const char * str) {
char buffer[SIZE_LINE];
int countWrd = 0;
strcpy(buffer, str);
for (char * pc = buffer; (pc = strtok(pc, " \n")) != NULL; pc = NULL) {
countWrd++;
}
return countWrd;
}