- #1
FOIWATER
Gold Member
- 434
- 12
Homework Statement
Hello,
I need to write a program which finds all words, lines, and paragraphs in a text file.
I am to scan the document character by character. When I get to the end of a line, I need to count the total number of words in that line and add it to the total. If the total is zero, it assumes that was the end of a paragraph.
I wrote the following program to do this.. it successfully scans any txt document and copies it, but it never stops.
it seems to me, that it never sees the end of a line and so, never exits the while(nextChar!=''\n') loop.
Any input appreciated. Here is my code.
Code:
#include <stdio.h>
#include <stdlib.h>
void initialize(int *p1,int *p2,int *p3,int *p4)
{
*p1=0;
*p2=0;
*p3=0;
*p4=0;
}
void processBlank(int *nextChar,int *wordsinLine,FILE *ctPtr)
{
while (*nextChar=='32') //32 is ascii code for a space.
{
printf("%c",*nextChar);
*nextChar=fgetc(ctPtr);
}
*wordsinLine+=1;
}
void copyText(int *nextChar,FILE *ctPtr)
{
while (*nextChar!='32')
{
printf("%c",*nextChar);
*nextChar=fgetc(ctPtr);
}
}
void updateCount(int *numWords,int *wordsinLine,int *numParagraphs,int *numLines)
{
*numWords+=*wordsinLine;
if (*wordsinLine==0)
*numParagraphs+=1;
*wordsinLine=0;
*numLines+=1;
}
void printTotal(int numWords,int numLines,int numParagraphs)
{
printf("\n\n\n\nTotal number of words is: %d\n\n",numWords);
printf("Total number of lines is: %d\n\n",numLines);
printf("Total number of paragraphs is: %d\n\n\n\n",numParagraphs);
}
void main()
{
int numWords,numLines,numParagraphs,wordsinLine;
initialize(&numWords,&numLines,&numParagraphs,&wordsinLine);
FILE *ctPtr;
int nextChar;
if ((ctPtr=fopen("Q2read.txt", "r"))==NULL)
printf("File could not be opened\n");
else
{
nextChar=fgetc(ctPtr);
while (nextChar!=EOF)
{
while (nextChar!='\n')
{
processBlank(&nextChar,&wordsinLine,ctPtr);
copyText(&nextChar,ctPtr);
}
updateCount(&numWords,&wordsinLine,&numParagraphs,&numLines);
}
printTotal(numWords,numLines,numParagraphs);
fclose(ctPtr);
}
}
Last edited by a moderator: