Hello, I have a problem counting the repeated words.

HI! I am reading Bjarne Stroustrup programming principles and practice using C++ 2nd. I am trying to count the repeated words. for example, if i input three same words, it should output that it repeated three times.
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
  
#include <iostream>
#include <string>
using namespace std;
int main()
{
	cout << "Enter: ";

	int num_repeated = 0;
	string previous = "";// 
	string current;

	if (cin >> current)
	{
		num_repeated++;
		if (previous == current)
		{
			cout << "total num of repeated words: " << num_repeated << " repeated word: " << current << endl;
		}
		previous = current; // assigns the value of current to previous
	}


	return 0;
}
Your logic is a bit off here.
Every time you input a word into current it will increment num_repeated regardless of whether it was equal to previous.
What you want to do is only increment if the current word is equal to previous word. Then, as soon as the current word isn't equal to the previous word, you'll have entered a different word, so we print and then reset num_repeated.
Beware of off-by-one bug.
Topic archived. No new replies allowed.