question  fstream , counting the occurences of words.

xxhashxx (8)   Link to this post
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:

hello
hi
hello
what
hello
hi
what


the code for input is
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
vector<string> input()
{
ifstream in_stream;


in_stream.open("input.txt");

vector<string> input;
string word;

if(in_stream.is_open())
{
while(in_stream >> word)
{
	input.push_back(word);
}
}

return input;
in_stream.close();
}



the code i use to get the output is:
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
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?
kempofighter (525)   Link to this post
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>.

Registered users can post in this forum.