fork download
  1. #include <iostream>
  2. #include <algorithm>
  3.  
  4. std::string pig_it(std::string str)
  5. {
  6. auto numOfSpaces = std::count(str.begin(), str.end(), ' ');
  7. int wordStart = 0;
  8. // возвращаем индекс пробела
  9. int wordEnd = str.find(" ");
  10. for (int word = 0; word <= numOfSpaces; ++word)
  11. {
  12. if (str[wordStart] == '!' || str[wordStart] == '?' || str[wordStart] == '.' || str[wordStart] == ',')
  13. {
  14. wordStart = wordStart + 2;
  15. if ((numOfSpaces - word) == 1) { wordEnd = str.size(); }
  16. else { wordEnd = str.find(" ", wordStart); }
  17. continue;
  18. }
  19. std::cout << "Debug: wordEnd = " << wordEnd << std::endl;
  20. str.insert(wordEnd, 1, str[wordStart]);
  21. str.insert(wordEnd + 1, "ay");
  22. str.erase(wordStart, 1);
  23. wordStart = wordEnd + 3;
  24. if ((numOfSpaces - word) == 1) { wordEnd = str.size(); }
  25. else { wordEnd = str.find(" ", wordStart); }
  26. }
  27. return str;
  28. }
  29.  
  30. int main(int argc, char * argv[])
  31. {
  32. std::cout << pig_it("Hello");
  33. }
  34.  
Runtime error #stdin #stdout #stderr 0.01s 5476KB
stdin
Standard input is empty
stdout
Debug: wordEnd = -1
stderr
terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::insert: __pos (which is 18446744073709551615) > this->size() (which is 5)