Hi, I done this exercise for the book I am reading. Here is the exercise:
Write a program to read strings from standard input
looking for duplicated words. The program should find places in the input
where one word is followed immediately by itself. Keep track of the largest
number of times a single repetition occurs and which word is repeated. Print
the maximum number of duplicates, or else print a message saying that no
word was repeated. For example, if the input is
how now now now brown cow cow
the output should indicate that the word now occurred three times.
Here is the code I wrote:
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 28 29
|
int main()
{
vector<string> v;
string s;
while (cin >> s)
v.push_back(s);
auto it = v.begin();
unsigned maxrepeats = 1, repeats = 1;
string prev, word;
while (it != v.end()) {
if (*it == prev) {
++repeats;
if (repeats > maxrepeats) {
maxrepeats = repeats;
word = *it;
}
}
else
repeats = 1;
prev = *it;
++it;
}
if (!word.empty())
cout << word << " occured " << maxrepeats << " times in a row." << endl;
else
cout << "There are no repeating words" << endl;
return 0;
}
|
The program seems to work okay but I can't help thinking that there is a better way to do it.
Anyone have any ideas? I'm just trying to improve my coding, it's not like this program needs to run extremely efficiently or anything.
Thanks!