I have actually managed to count most of the words in a sentence except for the last word, it somehow returns a value that is +1 of the actual letter count. I am unsure if it is because of a null pointer, or a hidden space somewhere, please help me understand how i can improve on the code to remove that error.
int main() {
char strc[255];
const char* delim = " ";
char* token;
int length;
char* magic = "magic";
printf("Enter a sentence, up to 255 characters:\n");
fgets(strc, 254, stdin);
token = strtok(strc, delim);
while (token != NULL) {
length = strlen(token);
printf("%s %d\n", token, length);
token = strtok(NULL, delim);
}
return 0;
}
the input and output is shown here:
input: Potatoes are tasty
output: Potatoes 8 are 3 tasty 6