I have an assignment that requires me to write a function to take in an array containing an English sentence and return the length of the longest word in that sentence. This is the code I have so far:
int longWordLength(char *s); // Function prototype
int main() {
char str[80], *p;
printf("Enter a string: \n");
fgets(str, 80, stdin);
if (p = strchr(str,'\n'))
*p = '\0'; //converts newline to null
printf("longWordLength(): %d\n", longWordLength(str));
return 0;
}
int longWordLength(char *s) {
int count = 0, max = 0;
while (*s++ != '\0') {
if ((*s >= 'a' && *s <= 'z') || (*s >= 'A'&& *s <= 'Z')) {
count++;
} else {
if (count > max) {
max = count;
count = 0;
} else
count = 0; // word is not the longest
}
}
return max;
}
I have tried for a long time to diagnose the issue but to no avail.
This works with certain test case like:
Test Case 1:
Enter a string:
I am happy.
longWordLength(): 5
but for a test case like Test Case 4:
Enter a string:
Hello
longWordLength(): 4 <- it prints 4 instead of 5.
I am not allowed to use any library other than the <string.h> as it is for my school assignment. Seeking anyone's kind guidance on my issue as I really can't seem to figure out the issue. Thank you in advanced.