Reputation: 47
I'm trying to create a dictionary that reads a file into a string vector and counts the number of times each unique word occurs. Here's what I have so far:
int main()
{
ifstream input1;
input1.open("Base_text.txt");
vector<string> base_file;
vector<int> base_count;
if (input1.fail())
{
cout<<"Input file 1 opening failed."<<endl;
exit(1);
}
make_dictionary(input1, base_file, base_count);
}
void make_dictionary(istream& file, vector<string>& words, vector<int>& count)
{
string word;
int i=0;
while (file>>word)
{
words.push_back(word);
cout<<words[i];
i++;
}
for (i=0; i<words.size(); i++)
{
if ((words[i+1]!=words[i]))
{
count.push_back(i);
}
}
Question 1: How do I get the vector to include spaces and recognize individual words? Question 2: Any ideas how to proceed with the second part (for loop)?
Upvotes: 0
Views: 1773
Reputation: 884
This is quite inefficient. You should use
std::map<string, int>
instead. It is both easier and more efficient.
Loop over the file. When you see a word, see if it's in the map. If it's not, add a new word with count 1. If it is, increment the count.
Upvotes: 5