I am writing a program that uses fstream to take in words from a file and then outputs the the number of times a word is reapeated:
my input is of the form:
void counter_out(vector<string> variable)
{
ofstream out_stream;
out_stream.open("output.txt");
int counter1 = 0;
int k = 0;
while(k < variable.size())
{
for(int i =0; i< (variable.size()); i++)
{
if(variable.at(k) == variable.at(i)){ counter1++;}
}
out_stream << "The word " << variable.at(k) << " occured " << counter1 << " times" << endl;
counter1 = 0;
k++;
}
out_stream.close();
}
but my output comes out to be
The word hello occured 3 times
The word hi occured 2 times
The word hello occured 3 times
The word what occured 2 times
The word hello occured 3 times
The word hi occured 2 times
The word what occured 2 times
because of the loop i used i keep getting repeated outputs, is there a way to simplify the output?
Another way is to not insert the same word multiple times. Check if the string is already in the vector. If it is, increment a counter. If it is not insert it and set the counter to 1 for that index. You'll need two arrays for this or a std::map. You could use a std::map if you are willing to learn how that container works. Alternatively you can create a second vector<unsigned int> with the same number of elements as the vector<string>. The vector<unsigned int> contains the counter for each element of the vector<string>. Understand? With std::map you create a std::map<std::string, unsigned int>.