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 123 124 125 126 127 128 129 130 131 132 133 134 135 136
|
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
/*********************************************************************/
/* Author: removed */
/* Course: CSC136 010 */
/* Assignment: #1 */
/* Due Date: September 11, 2010 */
/* Filename: p1.cpp */
/* Purpose: This program will determine the number of characters */
/* and lines in a file and print the number of times */
/* each word occurs and sort them accordingly. */
/*********************************************************************/
//Global struct.
struct wordRec
{
string word;
int wordCount;
};
wordRec list[1000];
//This function calculates the number
//of characters and lines in the file.
int charCount(ifstream& inf, int& a, int& b)
{
//Declare variables.
char c;
string d;
a, b = 0;
//Finds the number of characters.
inf.get(c);
inf.seekg(0, ios::end);
a = inf.tellg();
inf.seekg(0, ios::beg);
//Finds the number of lines.
while (getline(inf, d, '\n'))
b++;
}
void wordCalc(ifstream& inf, wordRec list[], int& count)
{
string s;
int i = 0;
while ((inf >> s) && (i < 1000))
{
list[i].word = s;
i++;
}
count = i;
}
void swap(wordRec& x, wordRec& y)
{
wordRec temp;
temp = x;
x = y;
y = temp;
}
void selSort(wordRec list[], int& elts)
{
int spot = 0;
int idxMin = 0;
int idxMax = elts;
for(int spot = 0; spot < elts - 1; spot++)
{
int idxMin = spot;
for(int idx = idxMin+1; idx < elts; idx++)
{
if(list[idx] < list[idxMin])
idxMin = idx;
if(idxMin != spot)
swap(list[idxMin],list[spot]);
else
{
swap(list[idxMin],list[idxMax]);
list[spot].wordCount++;
elts--;
}
}
}
}
int main()
{
//Delcare variables.
string fileName;
ifstream inf;
int charNum, newLine, count;
//Prompt user for filename and attempt to
//open that file.
cout << "Enter filename.\n >";
cin >> fileName;
inf.open(fileName.c_str());
//If the file doesn't open, display an
//error message and close the program.
if (!inf.is_open())
{
cout << "File " << fileName << " does not exist in the client's current directory." << endl;
exit(1);
}
//Finds the number of characters and lines.
charCount(inf, charNum, newLine);
//Reopen the program.
inf.close();
inf.clear();
inf.open(fileName.c_str());
//Function call to count the words.
wordCalc(inf, list, count);
selSort(list, count);
int i = 0;
for(i = 0; i < count; i++)
cout << list[i].word << endl;
return 0;
}
|