494 - Kindergarten Counting Game

 Kindergarten Counting Game 

Everybody sit down in a circle. Ok. Listen to me carefully.

``Woooooo, you scwewy wabbit!''

Now, could someone tell me how many words I just said?

 

Input and Output

Input to your program will consist of a series of lines, each line containing multiple words (at least one). A ``word'' is defined as a consecutive sequence of letters (upper and/or lower case).

 

Your program should output a word count for each line of input. Each word count should be printed on a separate line.

 

Sample Input

 

Meep Meep!
I tot I taw a putty tat.
I did! I did! I did taw a putty tat.
Shsssssssssh ... I am hunting wabbits. Heh Heh Heh Heh ...

 

Sample Output

 

2
7
10
9

--------------------------------------------------------------------------------------------
本题主要是判断一行字符串中有多少个word。判断方法为,一个字母开头到不是字母的字符结束为一个词。注意:也许一行的开头就是非字符
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<ctype.h>
 4 #define MAXN 1000
 5 char buf[MAXN];
 6 int main(){
 7     int len,j,sum;
 8     char oldch;
 9     while(fgets(buf,MAXN,stdin) != NULL){
10         len = strlen(buf);
11         sum = 0;
12         oldch = buf[0];
13         for(j = 1; j < len; j++){
14            if(isalpha(oldch) > 0  && isalpha(buf[j]) == 0){
15                 sum++;
16             }
17            oldch = buf[j];
18         }
19         printf("%d\n",sum);
20     }
21 }

刚开始犯的错误为:认为开端一定为字符,判断就使用了isalpha(j)  == 0 && isalpha(j-1) > 0,这导致开端为非字符的时候出现问题。

posted @ 2014-12-15 20:45  繁星苑  阅读(179)  评论(0编辑  收藏  举报