Q:

Write a program to read a sequence of strings from the standard input until either the same word occurs twice in succession or all the words have been read

0

Write a program to read a sequence of strings from the standard input until either the same word occurs twice in succession or all the words have been read. Use a while loop to read the text one word at a time. Use the break statement to terminate the loop if a word occurs twice in succession. Print the word if it occurs twice in succession, or else print a message saying that no word was repeated.

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 last, curr;
  bool hasRepeat = false;
  while (std::cin >> curr)
    if (curr == last) {
      std::cout << "Find repeated word: " << curr << std::endl;
      hasRepeat = true;
      break;
    } else {
      last = curr;
    }
  if (!hasRepeat)
    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