0

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

Darryl
  • 19
  • 1
  • 1
    fgets returns the newline at the end of the string. And you don't want to count that as a character. So you need to remove the newline at the end of the string before tokenizing. Have a look here: https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input and https://stackoverflow.com/questions/26672134/is-trailing-newline-necessary-in-fgets – Jerry Jeremiah Nov 14 '19 at 03:48
  • 2
    ... or include the newline as a delimiter. – Carl Norum Nov 14 '19 at 03:48
  • @CarlNorum good point. – Jerry Jeremiah Nov 14 '19 at 03:49
  • @JerryJeremiah i have actually looked through the references stated but i still have trouble forming the statements. they used strtok() functions, so does it mean in this case i have to add an if-else statement with strtok(token, '\n') to remove the newline?? – Darryl Nov 14 '19 at 03:58
  • Minus 1 not needed. `fgets(strc, szieof strc, stdin);` is fine and preferable. – chux - Reinstate Monica Nov 14 '19 at 04:11
  • 1
    @Darryl No, just change `const char* delim = " ";` to `const char* delim = " \n";` – user3386109 Nov 14 '19 at 04:11
  • `printf("Enter a sentence, up to 255 characters:\n");` is off by 1. Should be `printf("Enter a sentence, up to 254 characters:\n");` if one includes the `\n` as one of the characters, else, `printf("Enter a sentence, up to 253 characters:\n");` – chux - Reinstate Monica Nov 14 '19 at 04:12
  • @chux-ReinstateMonica Thank you for the tip!! ^^ – Darryl Nov 14 '19 at 05:06
  • @user3386109 okay! i'll try it out now! – Darryl Nov 14 '19 at 05:07

0 Answers0