K&R C Exercise 1-18 Solution

/*
 * Exercise 1-18 Write a program to remove trailing blanks and tabs from
 * each line of input, and to delete the entirely blank lines.
 *
 * fduan, Dec. 11, 2011 
 */
#include <stdio.h>

#define MAX_LEN	1000

int getline( char line[], int max_len );
void trim_line( char line[] );

int main()
{
	int len;
	char line[MAX_LEN] = { '\0' };

	while( ( len = getline( line, MAX_LEN ) ) > 0 )
	{
		trim_line( line );
		printf( "%s$\n", line );
	}
	return 0;
}

int getline( char line[], int max_len )
{
	int c, i, j;

	i = j = 0;
	while( ( c = getchar() ) != EOF && c != '\n' )
	{
		if( i < max_len - 2 )
			line[j++] = c;
		++i;
	}

	if( c == '\n' )
	{
		line[j++] = '\0'; ++i;
	}

	return i;
}

void trim_line( char line[] )
{
	int j, i = 0;
	while( line[i] != '\0' )
		++i;

	while( i-- > 0 && ( line[i] == ' ' || line[i] == '\t' ) )
		line[i] = '\0';
}

你可能感兴趣的:(c,delete,input,each,tabs)