/***********************************************
* CP-I warmup 1999-2000
* Problem #12
**********************************************/
/*
* Question:
*
* Write a complete C program to fold long lines into lines of
* 40 characters. A word must not be split across two lines. The
* program must scan lines from the user until he enters "STOP" as
* the first word of a line. A line is defined as a set of characters
* terminated by a '\n'.
*
* You can assume that there are no punctuation marks in the input.
*
* Example:
* input:
* this is a gift from all the would be cp2 team members
* to all the would be students
* STOP
* the output must be:
* this is a gift from all the would be cp2
* team members
* to all the would be students
*
* Note how a line has been split into two lines.
* Both the lines satisfy the condition that their length is utmost
* 40 characters, and no woed is split across lines.
*
* The fold command in UNIX can do this job.
*/
#include <stdio.h>
#include <string.h>
#define BUFFER_LENGTH 104
#define MAX_WORD_LENGTH 20
#define INPUT_TERMINATOR "STOP"
#define LINE_LENGTH 40
main()
{
char buffer[BUFFER_LENGTH]={'\0'};
char word[MAX_WORD_LENGTH]="";
char changed[BUFFER_LENGTH]={'\0'};
char ch='\n';
int i;
while(1)
{
word[0]='\0';
scanf("%s",word);
if(ch=='\n' && !strcmp(word,INPUT_TERMINATOR))
break;
ch=getchar();
strcat(buffer,word);
buffer[strlen(buffer)]=ch;
}
//printf("%s\nSCANNED\n",buffer);
printf("%s\n",changed);
fold(changed,buffer,LINE_LENGTH);
printf("Folded:\n%s\n",changed);
}
int fold(char *dest,char *old,int line_length)
{
char word[MAX_WORD_LENGTH]={'\0'};
char *prev,*temp;
int cur_len=0,i=0;
temp=old;
prev=old;
while(temp=strpbrk(temp," \t\n"))
{
if(cur_len+temp-prev>=line_length)
{
dest[strlen(dest)]='\n';
cur_len=0;
}
strncat(dest,prev,temp-prev);
dest[strlen(dest)]=temp[0];
cur_len+=temp-prev+1;
if(temp[0]=='\n')
cur_len=0;
temp++;
prev=temp;
}
}