EOF问题

EOF: http://baike.so.com/doc/630967.html

编写一个程序,把输入作为字符流读取,直到遇到EOF。令其报告输入中的大写字母个数和小写字母个数。

代码很简单,但是在编译通过之后运行时可能会遇到一个问题。读入字符结束应该按照如下准则运行:

在windows中,应先换行,再ctrl+z,再换行;

在linux中,ctrl+D

代码:

#include<stdio.h>
#include<ctype.h>
//#include<stdlib.h>
int main(void)
{
	char ch;
	int lower = 0,upper = 0;
	while ( (ch=getchar()) != EOF )
	{
		if ( islower(ch) ) lower++;//如果字符为小写字母,加一
		if ( isupper(ch) ) upper++;//如果字符为大写字母,加一
	}
	printf("lower: %d, upper: %d\n",lower,upper);
//	system("pause");
	return 0;
}


编写一个程序,把输入作为字符流读取,直到遇到EOF。令其报告每个单词的平均字母数。不要将空白字符记为单词中的字母。另外还需要考虑标点符号。

代码:

#include<stdio.h>
#include<ctype.h>
#include<stdbool.h>
int main()
{
	int words = 0,n = 0;
	char ch;
	bool inwords = false;//标识位 
	while( (ch = getchar()) != EOF )
	{
		if( !isspace(ch) && !ispunct(ch) )//如果非空白字符或标点符号,字符数加一 
		{
			words++;	
		}	
		if( !isspace(ch) && !inwords ) 
		{
			inwords = true;//新单词 
			n++;//统计单词个数 
		}	
		if( isspace(ch) && inwords )
		{
			inwords = false;//山穷水尽之时,即到达单词的尾部 
		} 
	}	
	printf("The average number of the words is %f\n",(float)words/(float)n);
	return 0;
}


结果如下:




灵活调用c标准库中的某些函数,可以大大提高我们解决问题的效率。例如上面两例中的ispunct(),islower(),isupper()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值