/* * Exercise 1-19 Write a function reverse(s) that reverses * that character string s. Use it to write a program that * reverses its input a line at a time. * * fduan, Dec. 11, 2011 */ #include <stdio.h> #define MAX_LEN 1000 int getline( char line[], int max_len ); void reverse( char line[] ); int main() { char line[MAX_LEN]; int len; while( ( len = getline( line, MAX_LEN ) ) > 0 ) { if( len > 0 ) reverse( line ); printf( "%s", 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++] = c; ++i; } line[j] = '\0'; return i; } void reverse( char line[] ) { int i, j; char tmp; i = j = 0; while( line[j] != '\n' ) ++j; for( --j; i < j; ++i, --j ) { tmp = line[i]; line[i] = line[j]; line[j] = tmp; } }