Hi ,
IM TRYING TO WRITE A TEXT FORMAT PROGRAM along the lines of the algorithm & pascal code found in similar named problem in "how to solve it by computer" R.G.Dromey.
What it does is take a "limit" from user and users input text...it outputs the re-formatted text as "limit" characters per line.
Im struggling with translating pascal's -
i. while not eof(input)
ii. if eoln(input)
iii. readln
iv. read(chr)
i am using C's -
i. while (chr!=EOF);
ii. if (getc(stdin)=='\n');
iii. ??
iv. chr=getc(stdin);
for the above ones respectively.
While i know this is not a pascal forum...i paste my c effort below and also 2 sample runs. Any help much appreciated.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
void textformat(int limit);
int main()
{
int limit;
printf("Enter the line length limit\n");
scanf("%d",&limit);
textformat(limit);
printf("\n\n");
system("pause");
return 0;
}
void textformat(int limit)
{
int i;
int linecnt;
int wordcnt;
int eol;
char chr;
char space;
char word[30];
char eoln;
FILE * outputFilePtr;
i=0;
wordcnt=0;
linecnt=0;
eol=FALSE;
chr=' ';
space=' ';
eoln='\n';
for(i=0;i<=29;i++)
{
word[i]=space;
}
outputFilePtr = fopen("afile.txt","w");
printf("Enter the text in multiple lines terminated by ctrl-z on a separate line\n");
while (chr!=EOF)
{
chr=getc(stdin);
wordcnt=wordcnt+1;
word[wordcnt]=chr;
if (chr==space)
{
if (eol && (wordcnt==1))
{
fprintf(outputFilePtr,"\n");
linecnt=0;
}
linecnt=linecnt+wordcnt;
if (linecnt>limit)
{
fprintf(outputFilePtr,"\n");
linecnt=wordcnt;
}
for (i=0;i<=wordcnt;i++)
{
fprintf(outputFilePtr,"%c",word[i]);
}
wordcnt=0;
eol=FALSE;
if(getc(stdin)==eoln)
{
eol=TRUE;
}
}
}
fprintf(outputFilePtr,"\n");
fclose(outputFilePtr);
printf("\n\n");
printf("The re-formatted text is in afile.txt");
}
Sample runs -
1.
Enter the line length limit
8
Enter the text in multiple lines terminated by ctrl-z on a separate line
wherever you go
^Z
The re-formatted text is in afile.txt
Press any key to continue . . .
o/p file -
wherever
ou
-------------
as seen - the lasst word is eaten up and also first character of second word ..thou "limit"-8 has been adhered to
2.
Enter the line length limit
40
Enter the text in multiple lines terminated by ctrl-z on a separate line
wherever you go
^Z
The re-formatted text is in afile.txt
Press any key to continue . . .
o/p file-
wherever ou
-----------------------
again the same issue.