2017-03-04 66 views
0

我剛剛開始學習C語言,並且正如話題所述,我必須編寫一個代碼來讀取另一個文本文件並計算「字符」,「單詞」和「句子」,直到達到EOF。我目前的問題是我無法產生正確的輸出。C編程:計數來自另一個文本文件的字符,單詞和行的數量

例如包含以下內容的文本文件...

the world 
is a great place. 
lovely 
and wonderful 

應以39個字符,9個字和4句並不知我獲得50(字符數)1(字)1(句子)輸出

這是我的代碼:

#include <stdio.h> 

int main() 
{ 
int x; 
char pos; 
unsigned int long charcount, wordcount, linecount; 

charcount = 0; 
wordcount = 0; 
linecount = 0; 

while(pos=getc(stdin) != EOF) 
{ 
    if (pos != '\n' && pos != ' ') 
    { 
    charcount+=1; 
    } 

    if (pos == ' ' || pos == '\n') 
    { 
    wordcount +=1; 
    } 

    if (pos == '\n') 
    { 
    linecount +=1; 
    } 

} 

    if (charcount>0) 
    { 
    wordcount+=1; 
    linecount+=1; 
    } 

printf("%lu %lu %lu\n", charcount, wordcount, linecount); 
return 0; 
} 

感謝任何形式的幫助或建議

+2

隨着'炭POS; ... while(pos = getc(stdin)',最好用'int pos;'來區分'fgetc()'返回的257個不同的值 - 儘管我懷疑這是你當前的問題, – chux

+0

你在哪裏打開文件? –

+0

您可能想要編輯您的問題,以表明您希望用戶將示例文本輸入到stdin中,或從代碼中刪除stdin。 – jrh

回答

2

由於運算符的優先級,下面兩行是相同的。

// Not what OP needs 
pos=getc(stdin) != EOF 
pos=(getc(stdin) != EOF) 

相反,使用()

while((pos=getc(stdin)) != EOF) 

使用int ch區分值從fgetc()這些都是unsigned char範圍和EOF值返回。通常有257個不同,對於char來說太多了。

int main() { 
    unsigned long character_count = 0; 
    unsigned long word_count = 0; 
    unsigned long line_count = 0; 
    unsigned long letter_count = 0; 
    int pos; 

    while((pos = getc(stdin)) != EOF) { 
    ... 

你可以查看你的字數策略了。 @Tony Tannous


對於我來說,我會算一個「字」任何時候發生了一封信,沒有遵循非信。這避免了一個問題@Tony Tannous和其他問題。同樣,我會將指定爲遵循'\n'或第一個字符的任何字符,並避免任何後循環計算。這處理了由Weather Vane評論的問題。

它也出現39是一個字母計數,而不是一個字符數@BLUEPIXY
建議使用<ctype.h>功能來測試信岬(isapha()

int previous = '\n'; 
while((pos = getc(stdin)) != EOF) { 
    character_count++; 
    if (isalpha(pos)) { 
    letter_count++; 
    if (!isalpha(previous)) word_count++; 
    } 
    if (previous == '\n') line_count++; 
    previous = pos; 
} 

printf("characters %lu\n", character_count); 
printf("letters %lu\n", letter_count); 
printf("words %lu\n", word_count); 
printf("lines %lu\n", line_count); 
+0

有了這兩個更正代碼給了'40 11 5'(最後一個換行符)和'40 10 4'(沒有最後一個換行符),但OP期待輸出「39 9 4」。 –

+0

@WeatherVane是的,OP的字符(字母),行和字數也需要工作。建議發佈代碼。 – chux

+0

終於!但很難複製/粘貼和編譯不一致的變量名稱。 –

相關問題