Questo è il main.cpp
#include <cstdio>
#include <iostream>
#include "conta.h"
#define WRONG_PARAM -1
#define ERROR_ON_OPEN_FILE -2
#define WRONG_MEM_ALLOC -3
#define REALLOC_ERROR -4
#define SIZE_WORD 20
int main(int argc, char**argv) {
FILE * input_file;
int N_words, n_lines = 0, substr_length;
int word_length, allocated_length = SIZE_WORD;
int n_substr = 0;
char *ptrWord = (char*)calloc(SIZE_WORD, sizeof(char)), *ptrReAlloc = NULL;
if (argc != 3) {
std::cerr << "Not enough parameters: missing the input file and/or the length of substr\n";
return WRONG_PARAM;
}
if (ptrWord == NULL) {
std::cerr << "Not enough memory\n";
return WRONG_MEM_ALLOC;
}
sscanf(argv[1], "%d", &substr_length);
input_file = fopen(argv[2], "r");
if (input_file == NULL) {
std::cerr << "Cannot open the input file\n";
return ERROR_ON_OPEN_FILE;
}
fscanf(input_file, "%d%*c", &N_words);
printf("%d\n",N_words);
while (n_lines < N_words) {
word_length = 0;
ptrWord[word_length] = (char) fgetc(input_file);
while ((ptrWord[word_length] != '\n') && (ptrWord[word_length] != EOF)) {
word_length++;
if (word_length >= allocated_length) {
allocated_length+=SIZE_WORD;
ptrReAlloc = (char *)realloc(ptrWord, allocated_length);
if (ptrReAlloc == NULL) { // in case of error
std::cerr << "ReAllocation Issue\n";
free(ptrWord);
ptrWord = NULL;
return REALLOC_ERROR;
}
ptrWord = ptrReAlloc; // assign the new ptr (even if it is the same as before)
}
ptrWord[word_length] = (char) fgetc(input_file);
}
ptrWord[word_length] = '\0';
n_substr += conta(ptrWord, substr_length);
n_lines++;
}
std::cout << "Total number of substr (n=" << substr_length << ") with 2 vowels: " << n_substr << '\n';
if (ptrWord != NULL){
free(ptrWord);
ptrWord = NULL;
}
return 0;
}
questo conta.cpp
#include "conta.h"
int isVowel(char a) {
char la = (char) tolower(a);
return (la == 'a' || la == 'e' || la == 'i' || la == 'o' || la == 'u');
}
int conta(char *S, int n) {
int tot = 0;
int Slength = strlen(S);
char *ptrToEnd = S + Slength - n;
int vowel_ctr;
if (Slength > n) {
for (; S <= ptrToEnd; S++) {
vowel_ctr = 0;
for (int j = 0; j < n && (vowel_ctr <= 2); j++) {
if (isVowel(S[j])) vowel_ctr++;
}
if (vowel_ctr == 2) tot++;
}
}
return tot;
}
questo conta.h
#ifndef LAB_02_CONTA_H
#define LAB_02_CONTA_H
#include <cstring>
#include <cctype>
int isVowel(char a);
int conta(char *S, int n);
#endif //LAB_02_CONTA_H
con file di testo
9
forExample
prova
astruso
pleonastico
zuzzurellone
procastinare
luculliano
mentecatto
supercalifragilisticexpialidocious