
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。判断方法为,一个字母开头到不是字母的字符结束为一个词。注意:也许一行的开头就是非字符
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define MAXN 1000
char buf[MAXN];
int main(){
int len,j,sum;
char oldch;
while(fgets(buf,MAXN,stdin) != NULL){
len = strlen(buf);
sum = ;
oldch = buf[];
for(j = ; j < len; j++){
if(isalpha(oldch) > && isalpha(buf[j]) == ){
sum++;
}
oldch = buf[j];
}
printf("%d\n",sum);
}
}
刚开始犯的错误为:认为开端一定为字符,判断就使用了isalpha(j) == 0 && isalpha(j-1) > 0,这导致开端为非字符的时候出现问题。