Character counting program
I am working or trying to figure out what the best way would be to count different characters in a file.
I need to open a file, read the file 1 character at a time, counting the different letters of the alphabet. Upper and lowercase letters count as the same, IE: 'A' and 'a' are the same.
Anything besides letters are totaled up together except spaces.
I attempted to convert a program that counts the frequency of words that you enter but I get several errors. I believe that these errors occur because I am trying to use a character instead of a string that the book used.
Before you start criticizing the code, please remember that I am a beginner C++ programmer and feel that this is over my head.
Can anyone help?
If this is not the best or simplist way to accomplish this, any suggestions?
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <iterator>
#include <algorithm>
#include <cctype>
#include <fstream>
using namespace std;
char toLower(char ch) { return tolower(ch); }
string & ToLower(string & st);
void display(const string & s);
int main()
{
vector<char> file;
// create output stream object for new file
ifstream fin("class.dat");
// check to make sure the file is opened
if(!fin.is_open())
{
cerr << "Could not open file for input!" << endl;
return 0;
}
char ch;
while (fin.get(ch)) //takes 1 ch at a time from file 1
file.push_back(ch);
fin.close();
// Place words in set
set<char> wordset;
transform(file.begin(), file.end(),
insert_iterator<set<char> > wordset,
wordset.begin()), ToLower);
cout << "Letters and Count" << endl;
for_each(wordset.begin(), wordset.end(), display);
cout << endl;
// place word and frequency in map
map<char, int> wordmap;
set<char>::iterator si;
for (si = wordset.begin(); si != wordset.end(); si++)
wordmap[*si] = count(file.begin(), file.end(),
*si);
// display map contents
cout << "Letter frequency:\n";
for (si = wordset.begin(); si != wordset.end(); si++)
cout << *si << ": " << wordmap[*si] << endl;
return 0;
}
string & ToLower(string & st)
{
transform(st.begin(), st.end(), st.begin(), toLower);
return st;
}
void display(const string & s)
{
cout << s << " ";
}