I am studying the c++ primer book and doing exercise 5.14. The exercise is:
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.
My code is as follow:
#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main()
{
string pre_word, word, max_repeate_word;
int repeate_times = 0; max_repeate_times = 0;
while (cin >> word) {
if (word == pre_word) {
++repeat_times;
}
else {
repeat_times = 1;
pre_word = word;
}
if (max_repeat_times < repeat_times) {
max_repeat_times = repeat_times;
max_repeat_word = pre_word;
}
}
if (max_repeat_times <= 1) {
cout << "no word was repeated" << endl;
}
else {
cout << "the word '" << max_repeat_word << "' occurred " << max_repeat_times << " times" << endl;
}
}
Is there anything wrong with my code? The program does not show any output when I input any string.
Aucun commentaire:
Enregistrer un commentaire