程序在计算 C 文件中的单词数时打印一个随机数

Program which prints a random number when it counts the number of words from a file in C

我正在尝试创建一个程序:

1.统计字数

2. 计算文件中单词的长度但是

我的问题是我注意到一些我没有预料到的东西,文件有四个单词,但是当它计算单词的长度时,程序会打印一个随机数 77

文件:

vasilis
giorgos
anastasia
nikos

代码:

#include<stdlib.h>
#include<string.h>

int main ()
{
    FILE *fp ;

    fp=fopen("C:\Users\TOSHIBA\Downloads\sample.txt","r");

    if (fp==NULL)
    {
        printf("the file is empty");
    }
    //count the number of words
    int counter =1;
    char ch;
    while((ch=fgetc(fp)) != EOF)
    {
       if (ch=='\n')
       {
           ++counter;
       }
    }

    fseek(fp,0,SEEK_SET);

    //count the length of words

    int length[counter];
    char ch1;
    int counter1 = 0 , i=0;

    while( (ch1 = getc(fp))!= EOF )
    {
        if (ch1 == '\n')
        {
            length[i]=counter1;
            i++;
            counter1=0;
            continue;
        }
        counter1++;

    }

    // print the length of every word

    for (i = 0; i < counter; i++)
    {
        printf("\n%d",length[i]);

    }
    return 0;
}

程序无法读取最后一个单词中的字符数,因为该单词末尾没有\n。代码应该这样修改—— enter image description here