1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
|
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
bool search(vector<string>& wordStorage,string& word);
int findIndex(vector<string>&wordStorage,string& word);
void sortVec(vector<int>&frequencies,vector<string>&wordStorage);
void print(vector<string>wordStorage,vector<int>frequencies);
int main()
{
//inputing file
ifstream infile ("example.txt");
//Test if opening was not successful
if(infile.fail())
{
cout << "Unable to open file.\n";
system("pause");
return 0;
}
string word;
vector <string> wordStorage;
vector <int> frequencies;
while(infile.good())
{
infile >> word;
for(int i = 0; i < word.length(); i++)
{
if( word[i] >= 'A' && word[i] <= 'Z')
{
word[i] = word[i] +32;
}
else if ( word[i] < 'A' || (word[i] > 'Z' && word[i] < 'a') || word[i] > 'z' )
{
word.erase(word.begin() + i);
i--;
}
}
if(search (wordStorage, word) == true)
{
frequencies[findIndex(wordStorage, word)]++;
}
else
{
wordStorage.push_back(word);
frequencies.push_back(1);
}
sortVec(frequencies,wordStorage);
}
print(wordStorage,frequencies);
system("pause");
return 0;
}
bool search(vector<string>&wordStorage,string& word) // finds the word if it is present.
{
for(int i = 0; i < wordStorage.size(); i++)
{
if( word == wordStorage[i])
{
return true;
}
}
return false;
}
int findIndex(vector<string>&wordStorage,string& word) //finds index of the word.
{
for(int i = 0; i < wordStorage.size(); i++)
{
if( word == wordStorage[i])
{
return i;
}
}
return 0;
}
void sortVec(vector<int>&frequencies,vector<string>&wordStorage) //Sorts Vector's.
{
for (int i = 0; i < frequencies.size(); i++)
{
for(int j = 0; i < frequencies.size() - 1; j++)
{
if(frequencies[j] > frequencies[j + 1])
{
int temp2 = frequencies[j];
frequencies[j] = frequencies[j+ 1];
frequencies[j + 1] = temp2;
string temp = wordStorage[j];
wordStorage[j] = wordStorage[j+ 1];
wordStorage[j + 1] = temp;
}
}
}
}
void print(vector<string>wordStorage,vector<int>frequencies) //Prints out the values.
{
int sumOfWords = 0;
for(int i = 0; i < frequencies.size(); i++)
{
sumOfWords = sumOfWords + frequencies[i];
}
cout << "Total Words= " <<sumOfWords << endl;
cout << "Distinct words= " << wordStorage.size() << endl;
}
|