2015-10-03 30 views
0

我試圖讓我的程序打印出測試字符串中單詞的數量,但它打印出的數字要大得多。例如,我的測試字符串有24個字,我的程序打印出102個。我想知道爲什麼它這樣做。程序打印字符數而不是字

#include <stdio.h> 
#include <stdlib.h> 
int main(int argc, char **argv) { 

    char testval[1024]="This is a test... this is only a test... for the next sixty seconds this will be a test of the emergency broadcasting system."; 

    int inWord=0; 
    int wordCount=0; 
    int i=0; 
    while(testval[i] != 0) { 
      if (testval[i]==' ') { 
        if (inWord) inWord=0; 
      } else { 
        if (!inWord) 
          inWord=1; 
          wordCount++; 
      } 
      i++; 
    } 

    printf("The number of words in testval is %d\n",wordCount); 
    return 0; 
} 


./numWords 
The number of words in testval is 102 
+0

你用調試器跟蹤了你的代碼片段嗎? – timrau

回答

1

對於每個空間,只需增加wordCount。最後添加一個,你有你的答案。

2
   if (!inWord) 
         inWord=1; 
         wordCount++; 

您錯過了一對{}以附上2條語句。 wordCount++;被執行爲全部爲非空格字符。

+0

我會檢查這是正確的答案 –

相關問題