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
|
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool CreateData ();
bool ReadData (vector<string> &words, vector<int> &wordCount);
void DisplayData (vector<string> &words, vector<int> &wordCount);
int FindWord (vector<string> &words, const string& line);
void Error (const string msg);
const string FILE_NAME = "Data.txt";
int main (void)
{
vector<string> words;
vector<int> wordCount;
if (!CreateData ())
Error ("\a\nCouldn't create Data.txt");
if (!ReadData (words, wordCount))
Error ("\a\nCouldn't read Data.txt");
DisplayData (words, wordCount);
system ("pause");
return EXIT_SUCCESS;
}
bool CreateData ()
{
static string names[] =
{
"Yana", "Anna", "Lisa", "Valerie", "Kim", "Anna",
"Yana", "Cathy", "Ellie", "Valerie", "Jelena", "Denise"
};
ofstream dest (FILE_NAME.c_str());
if (!dest)
return false;
for (string name : names)
{
dest << name << '\n';
}
return true;
}
bool ReadData (vector<string> &words, vector<int> &wordCount)
{
ifstream src (FILE_NAME.c_str ());
if (!src)
return false;
string line;
while (getline (src, line))
{
int idx = FindWord (words, line);
if (idx != -1) // word in the vector already
{
wordCount[idx]++;
}
else // need to create a new entry for the word and the count
{
words.push_back (line);
wordCount.push_back (1);
}
}
return true;
}
void DisplayData (vector<string> &words, vector<int> &wordCount)
{
if (words.size () != wordCount.size ())
Error ("Size of words and wordCount are not equal");
for (size_t i = 0; i < words.size(); i++)
{
cout << words[i] << '\t' << wordCount[i] << '\n';
}
}
int FindWord (vector<string> &words, const string& name)
{
for (size_t i = 0; i < words.size(); i++)
{
if (words[i] == name) // found
return static_cast<int>(i); // return index of name in words
}
return -1; // not found
}
void Error (const string msg)
{
cerr << "Error creating data.txt\n";
system ("pause");
exit (EXIT_FAILURE);
}
|