我正在嘗試創建一個程式:
1.統計字數
2.計算檔案中單詞的長度,但
我的問題是我注意到我沒想到檔案有四個單詞 word 但是當它計算單詞的長度時,程式會列印一個亂數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;
}
uj5u.com熱心網友回復:
該程式無法讀取最后一個單詞中的字符數,因為該單詞的末尾沒有 \n。代碼應該像這樣修改 - 在此處輸入影像描述
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/483015.html
上一篇:二維動態陣列指標訪問
下一篇:numpy陣列切片之間的區別
