Hi I am writing a program that counts the number of times each word occurs in a file. Then it prints a list of words with counts between 800 and 1000, sorted in the order of count. I am stuck on keeping a counter to see if the first word matches the next until a new word appears. In the main I am trying to open the file, read each word by word and call sort in the while loop to sort the vector. Then, in the for loop go through all the words and if the first word equals the second count++. I don't think that is how you keep a counter.
Here is the code:
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
vector<string> lines;
vector<int> second;
set<string> words;
multiset<string> multiwords;
void readLines(const char *filename)
{
string line;
ifstream infile;
infile.open(filename);
if (!infile)
{
cerr << filename << " cannot open" << endl;
return;
}
getline(infile, line);
while (!infile.eof())
{
lines.push_back(line);
getline(infile, line);
}
infile.close();
}
int binary_search(vector<string> &v, int size, int value)
{
int from = 0;
int to = size - 1;
while (from <= to)
{
int mid = (from + to) / 2;
int mid_count = multiwords.count(v[mid]);
if (value == mid_count)
return mid;
if (value < mid_count) to = mid - 1;
else from = mid + 1;
}
return from;
}
int main()
{
vector<string> words;
string x;
ifstream inFile;
int count = 0;
inFile.open("bible.txt");
if (!inFile)
{
cout << "Unable to open file";
exit(1);
}
while (inFile >> x){
sort(words.begin(), words.end());
}
for(int i = 0;i < second.size();i++)
{
if(x == x+1)
{
count++;
}
else
return;
}
inFile.close();
}
See Question&Answers more detail:os