494 - Kindergarten Counting Game

来源:互联网 发布:网络三巨头是什么意思 编辑:程序博客网 时间:2024/05/21 17:33

这道题目,我用getchar()一个一个读取并判断,因为题目中没有明确给出每一行的长度,用字符数组的话感觉不太好。

如果之前一直在读字母的话,而这次读到的不是字母的话,就说明一个单词结束了,可以增1;

那么如何判断之前一直在读字母呢?从一开始就设定一个begin = 1,当读取到第一个字母,就把begin设为0,直到读到非字母,再把begin设为1。

但是这道题目没有考虑单词中含标点的情况,如:“ mother’s ”


题目:

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


代码:

#include <stdio.h>#include <ctype.h>int main() {    char c;    int begin = 1;    int amount = 0;    while ((c = getchar()) != EOF) {        if (c != '\n') {            if (begin && isalpha(c)) {                begin = 0;            }            if (!begin && !isalpha(c)) {                begin = 1;                amount++;            }        }        else {            printf("%d\n", amount);            amount = 0;        }    }    return 0;}
0 0
原创粉丝点击