In: Computer Science
You are required to write a program to provide the statistics of a file (Number of letters, number of words, number of vowels, number of special characters and number of digits.
You should implement this problem as a class and call it FileContentStats which provides statistics about the number of letters, number of words, number of vowels, number of special characters, number of lines and number of digits. All of these should be private data members.
(Should be in C++ language)
C++ program for the given problem is provided below, please comment if any doubts:
Note: output and sample file used attached at the end.
C++ Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//The class
class FileContentStats
{
//private variables
private:
int vowelCount;
int lettersCount;
int specialcount;
int digitCount;
int wordCount;
int linesCount;
public:
//set the statistics
FileContentStats()
{
vowelCount=0;
lettersCount=0;
specialcount=0;
digitCount=0;
wordCount=0;
linesCount=0;
}
void countCharacterType(string filename)
{
int otherChar = 0;
//open the file
ifstream filePtr(filename);
//read the file
for(string fileLine; getline( filePtr, fileLine );
)
{
linesCount++;
wordCount++;
for (int itr = 0; itr < fileLine.length();
itr++) {
char lineChar =
fileLine[itr];
//process each character
if ( (lineChar >= 'a'
&& lineChar <= 'z') ||
(lineChar >= 'A' && lineChar <= 'Z') ) {
lineChar = tolower(lineChar);
//cout<<lineChar<<endl;
if (lineChar == 'a' || lineChar == 'e' || lineChar == 'i' ||
lineChar == 'o' || lineChar == 'u')
vowelCount++;
else
otherChar++;
}
else if (lineChar >=
'0' && lineChar <= '9')
digitCount++;
else if (lineChar == '
')
wordCount++;
else
specialcount++;
}
}
//set the letter count
lettersCount=(otherChar+vowelCount);
}
//display the statistics
void display()
{
cout << "Letters: " << lettersCount
<< endl;
cout << "Words: " << wordCount <<
endl;
cout << "Vowels: " << vowelCount
<< endl;
cout << "Digit: " << digitCount
<< endl;
cout <<"Lines: "<<linesCount
<<endl;
cout << "Special Character: " <<
specialcount << endl;
}
};
// Driver function.
int main()
{
//make the class object
FileContentStats f;
//process and display the file
f.countCharacterType("input.txt");
f.display();
//system("pause");
return 0;
}
Input file used:
Output: