Getting error in string code c++ std_out_of_range when using assign function

  c++, string

I’m trying to get the string from user and change any lower case to upper and vise versa. Also at the end of each word, I want to add EY to it. However when I run my code, I keep getting error std::out_of_rannge

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main()
{
    string sentence;
    string phrase("EY");
    int size;

    cout << "Enter the sentence that is going to be converted to Pig Latin" << endl;
    getline(cin, sentence);

    size = sentence.length();
    
    for (int i = 0; i < size; i++)
    {
        if (islower(sentence[i]))
        {
            sentence[i] = toupper(sentence[i]);
        }
        else if (isupper(sentence[i]))
        {
            sentence[i] = tolower(sentence[i]);
        }
    }

    for (int i = 0; i < size; i++)
    {
        if (sentence[i] == 32)
        sentence.assign(phrase, i, 2);
    }

    cout << sentence;
    return 0;
}

Source: Windows Questions C++

LEAVE A COMMENT