This is my little snippet that is giving me problems:
int main(int argc, char** argv) {
char string[75] = {0};
char *pChar;
int count = 0;
printf("String: ");
fgets(string, sizeof string, stdin);
printf("Numero parole: %d\n", countWords(string, strlen(string)));
// Suddivido la stringa nelle varie parole
pChar = strtok(string, " ");
while(pChar){
if(isWord(pChar, strlen(pChar))){
count += strlen(pChar);
}
pChar = strtok(NULL, " ");
}
printf("Lettere totali: %d\n", count);
return (EXIT_SUCCESS);
}
The problem is that no value is being assigned to count variable. I know there is something wrong but I still don’t know what’s wrong.
Thanks for helping ^^
P.S. I’m currently learning C so this probably is a stupid question.
P.P.S. As requested here’s the isWord function: (nevermind the comments they’re in italian)
// Controlla se è una parola
int isWord(char string[], int length){
int i = 0; // Contatore
int countAlpha = 0; // Se il carattere è alfabetico. Non vengono
// contate le parole che contengono numeri
// Inizio scorrendo tutta la stringa tranne l'ultimo carattere che è un
// terminatore di stringa
for(i; i < length - 1; i++){
// Se il carattere è alfabetico allora aumento il contatore isAlpha
if(isalpha(string[i])){
countAlpha++;
// Altrimenti il carattere non è una lettera
} else {
countAlpha = 0;
}
}
if(countAlpha == i){
return 0;
} else {
return 1;
}
}
If
countis not incrementing then it is because of one of the following:a)
strlen(pChar);returns 0b)
if(isWord(pChar, strlen(pChar)))is never truec)
while(pChar)is never validYou can validate what is working and what is not by making use of your interactive debugger and stepping through your code, line by line, as it executes.
Based on your additional changes since this was first posted, it seems the trouble is in your
isWordfunction. It seems that function is returning the opposite values that you meant. Change it so that theif(countAlpha == i)returns 1 (for true) and itselsereturns 0 (for false).