程序在计算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

代码应该这样修改:

while( (ch1 = getc(fp))!= EOF )
{
if (ch1 == 'n')
{
length[i]=counter1;
i++;
counter1=0;
continue;
}
counter1++;
}
length[i] = counter1; /* handle un-terminated last line */

最新更新