Skip to content

Commit

Permalink
Update ex5_14.cpp
Browse files Browse the repository at this point in the history
In the previous version, when you successively input same strings, then end the loop by ctrl+z(windows), the result is no duplicated words, which is not accord with our input.(eg. input three "123" and then ended with ctrl+z). 
The reason is that if the inputs are same from start, we will never enter the else branch where assign value to variable 'max_duplicated'.
So the operation on 'max_duplicated' should be done only when the 'count > max_duplicated.second + 1', which shows that continously duplicated inputs are tested. And when the input is not same with the previous, we should set the count for the new string to 1.
  • Loading branch information
AlexHuang1734 committed Oct 31, 2014
1 parent 4007a58 commit 2414003
Showing 1 changed file with 19 additions and 16 deletions.
35 changes: 19 additions & 16 deletions ch05/ex5_14.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,22 @@

using std::cout; using std::cin; using std::endl; using std::string; using std::pair;

int main()
{
pair<string, int> max_duplicated;
int count = 0;
for (string str, prestr; cin >> str; prestr = str)
{
if (str == prestr) { ++count; continue; }
else if (count > max_duplicated.second) max_duplicated = {prestr, count};
count = 0;
}

if (max_duplicated.first.empty()) cout << "There's no duplicated string." << endl;
else cout << "the word " << max_duplicated.first << " occurred " << max_duplicated.second+1 << " times. " << endl;

return 0;
}
int main() {

pair<string, int> max_duplicated;
int count = 1;
for (string str, prestr; cin >> str; prestr = str)
{
if (str == prestr) { ++count;}
else count = 1;

if (count > max_duplicated.second + 1) {
max_duplicated = { prestr, count };
}
}

if (max_duplicated.first.empty()) cout << "There's no duplicated string." << endl;
else cout << "the word " << max_duplicated.first << " occurred " << max_duplicated.second << " times. " << endl;

return 0;
}

0 comments on commit 2414003

Please sign in to comment.