UVA494 Kindergarten Counting Game

C语言程序员的一项重要工作就是封装功能函数。

问题链接UVA494 Kindergarten Counting Game

题意简述:幼儿园数单词游戏。输入若干句话,数一下每句有几个单词输出。

问题分析:实现方法有多种。可以用C语言的字符串函数strtok()来实现,也可以用字符流来实现。

程序说明用字符流实现时,封装了函数mygetchar()和mygetwords(),使得程序逻辑更加简洁,可阅读行强,通用行好。

AC的C语言程序如下:

/* UVA494 Kindergarten Counting Game */

#include <stdio.h>
#include <ctype.h>
#include <string.h>

char mygetchar()
{
    char c;

    c = getchar();
    if(c != '\n' && c != EOF)
        c = isalpha(c) ? c : ' ';

    return c;
}

int mygetwords()
{
    char c;
    int count = 0;

    while((c = mygetchar()) && c != '\n' && c != EOF) {
        if(isalpha(c))
            count++;
        while(isalpha(c))
            c = mygetchar();
    }

    return (count == 0 && c == EOF) ? -1 : count;
}

int main(void)
{
    int count;

    for(;;) {
        count = mygetwords();

        if(count < 0)
            break;

        printf("%d\n", count);
    }

    return 0;
}

另外一个AC的C语言程序如下:

/* UVA494 Kindergarten Counting Game */

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int mygets(char s[])
{
    int i = 0;
    char c;

    while((c = getchar()) && c != '\n' && c != EOF)
        s[i++] = isalpha(c) ? c : ' ';
    s[i] = '\0';

    return i;
}

int main(void)
{
    char buf[1024];
    char delim[] = " ";
    char *p;
    int count;

    while(mygets(buf)) {
        count = 0;
        p = strtok(buf, delim);
        while(p) {
             count++;
             p = strtok(NULL, delim);
        }
        printf("%d\n", count);
    }

    return 0;
}


posted on 2016-08-17 09:02  海岛Blog  阅读(190)  评论(0编辑  收藏  举报

导航