简体   繁体   中英

C program that counts the number of characters, words and lines in a given text, that may have blank lines?

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;

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM