zoukankan      html  css  js  c++  java
  • 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 != '
    ' && c != EOF)
            c = isalpha(c) ? c : ' ';
    
        return c;
    }
    
    int mygetwords()
    {
        char c;
        int count = 0;
    
        while((c = mygetchar()) && c != '
    ' && 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
    ", 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 != '
    ' && c != EOF)
            s[i++] = isalpha(c) ? c : ' ';
        s[i] = '';
    
        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
    ", count);
        }
    
        return 0;
    }


  • 相关阅读:
    【Demo 0011】多媒体播放器
    【Demo 0010】事件响应链
    【Demo 0009】表视图控制器
    【Demo 0008】标签控制器
    【Demo 0007】导航控制器
    【Demo 0006】iOS常用控件
    【Demo 0005】视图控制器
    【Demo 0004】屏幕、窗体及视图基础知识
    2019.7.16考试反思
    内网 可怜与超市题解 树形dp+合并
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564377.html
Copyright © 2011-2022 走看看