码迷,mamicode.com
首页 > 其他好文 > 详细

C - The C Answer (2nd Edition) - Exercise 1-18

时间:2015-07-27 23:04:22      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:exercise 1-18

/* Write a program to remove trailing blanks and tabs from each line of input, 
   and to delete entirely blank lines. */

#include <stdio.h>
#define MAXLINE 1000        /* maximum input line size */

int getline(char line[], int maxline);
int remove(char s[]);

/* remove trailing blanks and tabs, and delete blank lines */
main()
{
	char line[MAXLINE];     /* current input line */

	while((getline(line, MAXLINE)) > 0)
	{
		if(remove(line) > 0)
		{
			printf("%s", line);
		}
	}
	return 0;
}

/* getline: read a line into s, return length */
int getline(char s[], int lim)
{
	int c, i, j;
	j = 0;
	for(i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
	{
		if(i < lim - 2)
		{
			s[j] = c;       /* line still in boundaries */
			++j;
		}
	}
	if(c == '\n')
	{
		s[j] = c;
		++j;
		++i;
	}
	s[j] = '\0';
	return i;
}

/* remove trailing blanks and tabs from character string s */
int remove(char s[])
{
	int i;
	i = 0;
	while(s[i] != '\n')     /* find newline character */
	{
		++i;
	}
	--i;                    /* back off from '\n' */
	while(i >= 0 && (s[i] == ' ' || s[i] == '\t'))
	{
		--i;
	}
	if(i >= 0)              /* is it a non-blank line? */
	{
		++i;
		s[i] = '\n';        /* put newline character back */
		++i;
		s[i] = '\0';        /* terminate the string */
	}
	return i;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

C - The C Answer (2nd Edition) - Exercise 1-18

标签:exercise 1-18

原文地址:http://blog.csdn.net/troubleshooter/article/details/47091779

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