1
votes

Here are the specifications.

Every byte read from stdin counts as a character except EOF. Words are defined as contiguous sequences of letters (a through z, A through Z) and the apostrophe ( ', value 39 decimal) separated by any character outside these ranges. Lines are defined as contiguous sequences of characters separated by newline characters ('\n'). Characters beyond the final newline character will not be included in the line count.

My code seems to work for simple inputs, but when I try to input a large file with multiple paragraphs separated by blank lines my numbers are thrown off, with the word count and character being too high.

So far I have

#include <stdio.h>

int main(){

   char ch;
   unsigned int long linecount, wordcount, charcount;
   int u;
   linecount=0;
   wordcount=0;
   charcount=0;


   while((ch=getc(stdin))!=EOF){


       if (ch !='\n') {++charcount;}
       if (ch==' ' || ch=='\n') {++wordcount;}
       if (ch=='\n') {++linecount;}

     }
   if(charcount>0){
      ++wordcount;
      ++linecount;
   }

   printf( "%lu %lu %lu\n", charcount, wordcount, linecount );

   return 0;

}
1
You increment wordcount whenever you encounter a space or newline character. Rethink what a word is. It is not simply a sequence of spaces and newline characters.Jim Rogers
"My code seems to work for simple inputs" are you sure? Just feed it three blanks and a new-line.alk
char ch; ==> int ch;pmg

1 Answers

-1
votes

When you encounter blank lines, you'll see \n twice in a row. Look for these occurrences and each time you see them, decrement your word count by one.