K&R C Exercise 1-18 Solution

来源:互联网 发布:六肖公式算法大公开 编辑:程序博客网 时间:2024/04/28 19:02
/* * 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_LEN1000int 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';}