This is my solution to K&R Ex 1-18 which requires us to remove all trailing blanks and spaces from a string. I specifically wanted to use a separate function for processing the input (via gtLine()) to promote code re-usability. Please tell me ways in which I could have made my program shorter/better. Also, please point out anything wrong that you might find with my programming logic or algorithm.
#include<stdio.h>
#define MAXLEN 100
#define STORELEN 1000
#define T 1
#define F 0
int gtLine(char[]);
int process(char[],int);
void append(char[],char[],int);
main()
{
char line[MAXLEN],str[STORELEN];
int len,pos;
len=pos=0;
while((len=gtLine(line))>0)
{
len=process(line,len);
append(str,line,pos);
pos+=len;
}
printf("\nThe text : %s\n" AC_RESET,str);
return 0;
}
/*** Gets a line for Input from the user Till EOF or a new line is read. Returns the position of NULL ***/
int gtLine(char arr[])
{
int c,i;
for(i=0;(i<MAXLEN-1) && ((c=getchar())!=EOF) && (c!='\n');++i)
arr[i]=c;
if(c=='\n')
{
arr[i]=c;
++i;
}
arr[i]='\0';
return i;
}
/*** Processes the input string to remove all trailing spaces from the text. ***/
/*** Returns the new length of string ***/
int process(char arr[],int len)
{
int pc,nl;
nl=F; // New line Flag
if(arr[0]!='\n')
{
pc=arr[len-1];
while(pc==' '||pc=='\t'||pc=='\n')
{
if(pc=='\n')
nl=T; // Set to 1 if at anypoint a new line character is encountered.
--len;
if(len!=0)
pc=arr[len-1];
}
if(nl==T && len!=0)
arr[len++]='\n';
arr[len]='\0';
return len;
}
else
{
arr[0]='\0';
return (len=0);
}
}
/*** Appends the string from[] to the end of to[] from to[pos] where pos= position of NULL in to[] ***/
void append(char to[],char from[],int pos)
{
int i=0;
while((pos<STORELEN) && ((to[pos]=from[i])!='\0'))
{
++i;
++pos;
}
to[pos]='\0';
}