#include <iostream>
#include <algorithm>

std::string pig_it(std::string str)
{
    auto numOfSpaces = std::count(str.begin(), str.end(), ' ');
    int wordStart = 0;
    // возвращаем индекс пробела
    int wordEnd = str.find(" ");
    for (int word = 0; word <= numOfSpaces; ++word)
    {
        if (str[wordStart] == '!' || str[wordStart] == '?' || str[wordStart] == '.' || str[wordStart] == ',')
        {
            wordStart = wordStart + 2;
            if ((numOfSpaces - word) == 1) { wordEnd = str.size(); }
            else { wordEnd = str.find(" ", wordStart); }
            continue;
        }
        std::cout << "Debug: wordEnd = " << wordEnd << std::endl;
        str.insert(wordEnd, 1, str[wordStart]);
        str.insert(wordEnd + 1, "ay");
        str.erase(wordStart, 1);
        wordStart = wordEnd + 3;
        if ((numOfSpaces - word) == 1) { wordEnd = str.size(); }
        else { wordEnd = str.find(" ", wordStart); }
    }
    return str;
}

int main(int argc, char * argv[])
{
    std::cout << pig_it("Hello");
}
