The way my program handles lines with no blank before the nth column is it reports an error and doesnt fold the line.
I seperated the program into 2 functions for simplicity:
--1. Getline - gets a line, replaces tabs with the proper number of blanks and takes care of overflow (MAX_SIZE)
--2. Fold_line -- folds the line based on LINE_WIDTH constant. if no blanks before the nth column returns 0 and reports an error.
If you guys think i did something wrong tell me. I think i did everything this exercise asks for, but if you think i can improve it somehow or take care of the long lines in a better way, id appreciate if you told me .
Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
#define LINE_WIDTH 10
#define TAB_STOP 8
int Getline(char line[]) /* replaces tabs with the proper amounts of blanks & takes care of overflow */
{
int c, counter, x, y, tmp;
counter = x = y = tmp = 0;
while((c=getchar())!='\n')
{
if(c == EOF || x == MAX_SIZE - 2) return 0;
if(counter != TAB_STOP + 1) counter++;
else counter = 0;
if(c=='\t')
{
tmp = TAB_STOP+1 - counter;
for(y=0; y<tmp; y++) line[x++]=' ';
counter = 0;
}
else line[x++]=c;
}
line[x]='\n'; x++;
line[x]='\0';
return x;
}
int Fold_line(char line[], int x) /* folds lines, reports an error if there are no blanks before the nth column */
{
int pom=x;
int counter, blank_location, word_len;
counter = blank_location = word_len =0;
for(x=0; x<pom; x++)
{
if(line[x]==' ') { blank_location=x; word_len = 0; }
else word_len++;
if(counter == LINE_WIDTH+1 && word_len < LINE_WIDTH )
{
if(line[x]==' ') { line[x]='\n'; word_len=0; counter=0; }
else { line[blank_location]='\n'; counter = word_len; }
}
else if(counter >= LINE_WIDTH+1 && word_len >= LINE_WIDTH + 1) return 0;
counter++;
}
return 1;
}
int main(int argc, char *argv[])
{
int x=0;
int tmp=0;
char line[MAX_SIZE];
do{
if((x = Getline(line))==0) return 0;
if((tmp = Fold_line(line, x))==0) printf("Sequence of characters found without a blank before the %d. column.\n", LINE_WIDTH+1);
else printf("%s", line);
}while(x!=0);
printf("Press any key to continue\n\n");
getchar();
return 0;
}