/* This program reformats the standard input, except for the first line which contains the new maximum line length, line_length, to at most line_length characters per line. The program writes to the standard output. Lines are broken at spaces. */ #include #include #define MAX_WORD_LENGTH 80 /* max length of word in input */ main() { int line_length, /* max length of line in output */ curr_line_length = 0, /* number of chars printed so far in current line */ word_length; /* length of current word */ char word[ MAX_WORD_LENGTH + 1 ]; /* buffer to read word + 1 is for terminating '\0' */ scanf( "%d", &line_length ); /* 1st line of input has line length */ while ( scanf( "%s", word ) != EOF ) { /* determine length of current word */ for ( word_length = 0; word[ word_length ] != '\0'; word_length++ ) ; if ( word_length > line_length ) printf( "\nERROR: word length exceeds line length" ); if ( curr_line_length == 0 ) { /* first word to write? */ printf( "%s", word ); curr_line_length = word_length; } else { /* +1 is for space */ curr_line_length += word_length + 1; /* if word won't fit on current line, start a new line */ if ( curr_line_length > line_length ) { printf( "\n%s", word ); curr_line_length = word_length; } else /* word fits, add space and word to current line */ printf( " %s", word ); } } return EXIT_SUCCESS; }