2009-06-20

A modification to an entry to the programming challenge "Letter Frequency"

One of the entries to the programming challenge "Letter Frequency" had used reading from standard input to read the text file. It was discussed on the Usenet group comp.lang.c++ that it could be that some OS-dependent optimization occur in this case.

So, I have rewritten that entry somehat to read from a file instead of standard input, the code is posted below. I will include this into the challenge as well and possibly put the original codeunder a separate heading.

#include "limits.h"
#include "stdio.h"
#include "fstream"
#include "ctype.h"
int main(int argc,char** argv)
{
   size_t f [UCHAR_MAX+1] = { 0 };
   size_t size = 0;
   int c;

   std::ifstream inp(argv[1]);

   while ( inp )
   {
      c = inp.get();
      f [c]++;
      size++;
   }
   inp.close();

   for ( c = 0; c <= UCHAR_MAX; ++c )
      if ( islower( c ) )
         f [toupper( c )] += f [c];

   for ( c = 0; c <= UCHAR_MAX; ++c )
      if ( f [c] && !islower( c ) && isprint( c ) )
         printf( "%c %.3f%%\n", c, f[c]*100.0/size );

   return 0;
}

0 kommentarer:

Post a Comment