From 6659049d8e26e993812c04fc5b6c366ca8b9665f Mon Sep 17 00:00:00 2001 From: Moedrian Date: Wed, 17 May 2023 13:44:30 +0800 Subject: [PATCH] Update 5.14.cpp make the assignment happen in the loop --- ch5/5.14.cpp | 47 +++++++++++++++++++++++------------------------ 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/ch5/5.14.cpp b/ch5/5.14.cpp index 22f5c7f..e098b36 100644 --- a/ch5/5.14.cpp +++ b/ch5/5.14.cpp @@ -2,29 +2,28 @@ #include int main() { - std::string word, duplicatedWord, maxDuplicatedWord; - unsigned cnt = 0, maxCnt = 0; - while (std::cin >> word) { - if (word == duplicatedWord) - ++cnt; - else { - if (cnt > maxCnt) { - maxDuplicatedWord = duplicatedWord; - maxCnt = cnt; - } - duplicatedWord = word; - cnt = 1; + + std::string input, before, maxWord; + unsigned max = 0, cnt = 0; + + while(std::cin >> input) { + ++cnt; + + if (before != input) { + if (max < cnt) { + max = cnt; + maxWord = before; + } + cnt = 0; + } + + before = input; } - } - if (cnt > maxCnt) { - maxDuplicatedWord = duplicatedWord; - maxCnt = cnt; - } - if (maxCnt > 1) { - std::cout << maxDuplicatedWord << " occurs " << maxCnt - << " times." << std::endl; - } else { - std::cout << "No word was repeated." << std::endl; - } - return 0; + + if (!maxWord.empty()) + std::cout << maxWord << " occurred " << max << " times." << std::endl; + else + std::cout << "No duplicates" << std::endl; + + return 0; }