码迷,mamicode.com
首页 > 编程语言 > 详细

C语言K&R习题系列——使用缓冲区函数接受长字符输入

时间:2015-03-15 07:12:44      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:c

原题:


Write a program to print all input lines that are longer than 80 characters. 



,实现起来不算难,关键是用到了缓冲区,很不错的一种思想!

/* Write a program to print all input lines
 * that are longer than 80 characters
 */
 
 #include < stdio.h >
 
 #define MINLENGTH 81
 
 /*readbuff: read all input characters*/
 int readbuff ( char *buffer )
 {
	size_t i = 0;
	int c;
	
	while( i < MINLENGTH )
	{
		c = getchar();
		
		if ( c == EOF )
		{
			return -1;
		}
		if ( c == ‘\n‘ )
		{
			return 0;
		}
		
		buffer[i++] = c;
	}
	
	return 1;
 }
 
 /*copyread: copy the inputs that longer than 80 characters*/
 int copyread ( char *buffer )
 {
	size_t i;
	int c;
	int status;
	
	status = 1;
	
	for ( i = 0; i < MINLENGTH; i++ )
	{
		putchar ( buffer[i++] );
	}
	while ( status == 1 )
	{
		c = getchar();
		if ( c == EOF )
		{
			status = -1;
		}
		else if ( c == ‘\n‘ )
		{
			status = 0;
		}
		else
		{
			putchar(c);
		}
		putchar ( ‘\n‘ );
	}
	return status;
 }
 
 /*print the inputs that longer than 80 characters*/
 main ( void )
 {
	int status;
	char buffer[MINLENGTH];
	
	/*initialize*/
	status = 1;
	while ( status != -1 )
	{
		status = readbuff ( buffer );
		if ( status == 1 )
		{
			status = copyread ( buffer );
		}
		
	}
	
	return 0;
 }


C语言K&R习题系列——使用缓冲区函数接受长字符输入

标签:c

原文地址:http://anglecode.blog.51cto.com/5628271/1620417

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!