Joined: Sun May 25, 2008 5:34 pm Posts: 95 Has thanked: 2 time Have thanks: 1 time
Code:
/* * Formats the input text into 75 character wide lines. Takes each * non-blank unit as a word, and fits as many as possible on each * line. It separates words by one space, unless the word ends in * a period, !, or ?, and the next word starts with a capitol, * in which case it gets two spaces. */ #include <stdio.h> #include <string.h> #include <ctype.h>
#define WIDTH 75 /* Width of a line. */ #define WORDSIZE 50 /* Storage size of input word. */
main() { char line[WIDTH+1]; /* Output line. */ char word[WORDSIZE]; /* Input word. */ int linesize; /* Accumulated line size. */ int wordsize; /* Size of inbound word. */ int numspace; /* Number of separating spaces. */
/* Read all the words in the input file. */ while(scanf("%s", word) == 1) { /* How long is it? */ wordsize = strlen(word);
/* Decide how many spaces need to after the word. */ if(linesize == 0) numspace = 0; else if ((line[linesize-1] == '.' || line[linesize-1] == '?' || line[linesize-1] == '!') && isupper(word[0])) numspace = 2; else numspace = 1;
/* See if it fits on the line, complete with separating space. */ if(linesize + wordsize + numspace > WIDTH) { /* Too long. Spit out the line, and reset. */ printf("%s\n", line); strcpy(line, word); linesize = wordsize; } else { /* Fits. Add it to the line. */ strcat(line, " " + (2 - numspace)); strcat(line, word); linesize += wordsize + numspace; } }
/* Print the last line. */ printf("%s\n", line); }