2011-12-09 47 views
0

嘿,我一直在試圖計數的單詞數在我的文本文件,加載了一堆話一個劊子手遊戲,從C,但我打磚壁。我使用的這段代碼應該是我正在使用這段代碼;計數採用C從文本的單詞數文件

FILE *infile; 
     FILE *infile; 
char buffer[MAXWORD]; 
int iwant, nwords; 
iwant = rand() %nwords; 

// Open the file 

infile = fopen("words.txt", "r"); 

// If the file cannot be opened 

if (infile ==NULL) { 

    printf("The file can not be opened!\n"); 
    exit(1); 
} 

// The Word count 

while (fscanf(infile, "%s", buffer) == 1) { 

    ++nwords; 
} 

printf("There are %i words. \n", nwords); 

    fclose(infile); 
} 

如果任何人有任何建議如何解決這個問題,我將非常感激。

文本文件每行1個字,用850個字。

應用緩衝區的建議,但字數仍出來的1606419282.

校正把

int nwords = 0; 

工作過!非常感謝你!

+1

不是答案 - 但請參閱http://www.leancrew.com/all-this/2011/12/more-shell-less-egg/ –

+0

@MartinBeckett哈,今天在reddit上也看到了,呃? – Rooke

+0

@Rooke昨天news.ycombinator.com! –

回答

1

變量nwords永遠不會初始化。你不能假定它從零開始。

如果是這樣,你會在下一行得到一個崩潰( 「被零除」),其目的躲開我:

iwant = rand() %nwords; 

因此,通過

更換

int iwant, nwords; 
iwant = rand() %nwords; 

int nwords = 0; 
2

所以的話是每行一個條目?

while (fscanf(infile, "%s", &nwords) == 1); { 
    ++nwords; 
} 

不按照您的想法做。它用nwords讀取一個字符串,這不是一個字符串。 如果你想這樣做,這樣,你需要分配一個字符串即char buffer[XXX]這是足夠長,以包含您的數據文件和使用時間最長的留置權:

while (fscanf(infile, "%s", buffer) == 1) { 
    ++nwords; 
} 
+0

as @cnicutar發現';'在循環中的'{'之前意味着循環只運行一次。 –

0
  1. 看完後的第一個字和空白之後,你的fscanf換貨政... RNS輸入緩衝區的空白。所以,下次你閱讀空文字。
  2. 更改建議:

    的fscanf(INFILE 「%s」,&緩衝)//注意空間!而&緩衝

    之前它會甩開所有空白,直到下一個單詞。它應該工作。


附:最好不要使用[f] scanf :-)

相關問題