fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4.  
  5. void print_nth_word(std::istream& in, std::size_t nth){
  6. std::string word;
  7. std::size_t n{};
  8.  
  9. while(in >> word){
  10. if(++n % nth == 0)
  11. std::cout << word << '\n';
  12. }
  13. }
  14.  
  15.  
  16. void print_nth_word(const std::string& s, std::size_t nth){
  17. std::string word;
  18. std::size_t n{};
  19.  
  20. for(auto it = s.begin(); it < s.end(); ++it){
  21. while(it < s.end() && *it == ' ')
  22. ++it;
  23.  
  24. if(it == s.end())
  25. return;
  26.  
  27. word.clear();
  28.  
  29. while(it < s.end() && *it != ' ')
  30. word.push_back(*it++);
  31.  
  32. if(++n % nth == 0)
  33. std::cout << word << '\n';
  34. }
  35. }
  36.  
  37. #include <sstream>
  38.  
  39. int main(){
  40. std::string text = "Tell the truth, Nobody will do Anything.";
  41. std::stringstream stream{text};
  42.  
  43. print_nth_word(text, 3);
  44. print_nth_word(stream, 3);
  45. }
  46.  
Success #stdin #stdout 0.01s 5620KB
stdin
Standard input is empty
stdout
truth,
do
truth,
do