Q:

Write a program to read strings from standard input looking for duplicated words

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <iostream>
#include <string>

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;
    }
  }
  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;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now