user14535755
user14535755

Reputation:

Why is there an extra line after my output?

#include <stdio.h>
#include <ctype.h>
int main()
{
    char str[100];
    char splitStrings[10][10];
    int i, j, cnt;

    printf("Enter a sentence, up to 255 charcters: \n");
    fgets(str, sizeof str, stdin);

    j = 0; cnt = 0;
    for (i = 0; i <= (strlen(str)); i++)
    {
        if (!ispunct(str[i]) == ' ' || isalpha(str[i]) == '\0')
        {
            splitStrings[cnt][j] = '\0';
            cnt++;  //for next word
            j = 0;    //for next word, init index to 0
        }
        else
        {
            splitStrings[cnt][j] = str[i];
            j++;
        }
    }
    for (i = 0; i < cnt; i++)
        printf("\n%s %d \n",  splitStrings[i], strlen(splitStrings[i]));
    return 0;
}

Here is my code, I am trying to input a sentence and it will spilt up the string by words and count the number of letter. But it appear there an additional 0 in my output? And how do I get rid of it output

Upvotes: 1

Views: 75

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

fgets() will put a newline character it read into the buffer when the input is short enough to fit (as in the example data).

The newline character is not an alphabet, so isalpha(str[i]) == '\0' will become true and it moves on next word.

Then, the next charcter is terminating null-character. (it is processed because the loop condition is i <= (strlen(str))) It is also not an alphabet, so it also moves on next word.

There are no characters between the newline character and the terminating null-character, so it is printed as zero-character word.

Upvotes: 2

Related Questions