/*
   Name: Assignment 5
   Author: muguangde
   Date: 2014-08-07-11:29 AM
   Description: This is a simple program to read a text file, and
   output it in a new file, 10 words per line. Also, count the number
   of words, letters and length of words.
*/

#include <iostream>
#include<cstdlib>
#include<string>
#include<fstream>
#include<iomanip>
#include<cctype>

const int maximumLength=11;//max size is 10. leave slot 0 empty.
const int alpha=26;

using namespace std;

int main()
{
    int countWords[maximumLength];
    int countAlpha[alpha];
    void readAndPrint(int [],int []);
    //initialize the counters
    for(int i=0;i<maximumLength;i++)
        countWords[i]=0;
    for(int j=0;j<alpha;j++)
        countAlpha[j]=0;

    readAndPrint(countWords, countAlpha);

    system("PAUSE");
    return 0;
}

//Function to read the file and do all the calculation, then output
void readAndPrint(int countWords[],int countAlpha[])
{
   string word;
   string::size_type size;
   int totalWords=0;
   int numAlpha=0;
   ofstream outfile;
   ifstream infile;
   infile.open("catinhat.txt");
   //If the input file can't be opened
   if(!infile.is_open()){
    cout<<endl<<"Error: can not open file"<<endl;
    system("PAUSE");
    exit(1);
   }
   //If the output file can't be opened
   outfile.open("output.txt");
    if(!outfile.is_open())
   {
       cout<<"Error: can not open output file"<<endl;
       system("PAUSE");
       exit(1);
   }
   //Read the file word by word, check each letter to see whether
   //they are alphabet
   while(!infile.eof()&& infile>>word)
   {
       totalWords++;
       //Initialize number of letter for each word
       numAlpha=0;
       size=word.length();
       //Be careful of each word of each sentence
       //check each letter in the word
       for(unsigned int m=0;m<size;m++)
       {
           if(isalpha((int)word[m]))
              numAlpha++;
       }
       countWords[numAlpha]++;
       //Output 10 words per line
       if((totalWords-1)%10==0 && totalWords!=1)
       outfile<<endl;
       outfile<<word<<' ';
       //Calculate the number of letter
       for(unsigned int j=0;j<word.length();j++)
       {
           if(isalpha(word[j]))
            {
            word[j]=toupper(word[j]);
            countAlpha[word[j]-'A']++;
            }
       }
   }
   outfile<<"\n**********************************************"<<endl;
   outfile<<endl<<"There are "<<totalWords<<" words totally"<<endl;
   outfile<<"**********************************************"<<endl;

   for(int i=1;i<maximumLength;i++)
   outfile<<"Number of "<<setw(2)<<setiosflags(ios::right)<<i
          <<" Letter word:"<<' '<<setw(4)
          <<setiosflags(ios::right)<<countWords[i]<<endl;
   outfile<<"**********************************************"<<endl;

   for(int k=0;k<alpha;k++)
   outfile<<(char)('A'+k)<<": "<<setw(4)
          <<setiosflags(ios::right)<<countAlpha[k]<<endl;

   infile.close();
   outfile.close();
}


  
回到主页 回到目录