UVA494 Kindergarten Counting Game

 2023-09-05 阅读 205 评论 0

摘要:C语言程序员的一项重要工作就是封装功能函数。 问题链接:UVA494 Kindergarten Counting Game。 题意简述:幼儿园数单词游戏。输入若干句话,数一下每句有几个单词输出。 问题分析:实现方法有多种。可以用C语言的字符串函数strtok()来实现,

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;
}


转载于:https://www.cnblogs.com/tigerisland/p/7564377.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/1018.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息