2015-10-03 29 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

我会检查这是正确的答案 –

相关问题