0

我正在开发一个英语到猪拉丁语转换器,作为一个学习基本 c++ 的项目,出于某种原因,即使它编译正确,它也说它终止了。这是控制台输出:

input a word. 
hello
terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::insert: __pos (which is 5) > this->size() (which is 4)
Aborted (core dumped)

这是完整的程序代码:


#include <iostream>
#include <string>

using namespace std;

int main()
{
 //get's user input and assigns it as input
    string input;
    cout << "input a word. " << endl;
    getline(cin,input);

//defines output
    string output = input.assign(input);

//reads length of the input
    int length = input.size();

//get's the first letter of input and set's firstLetter to be that letter
    string firstLetter = input.assign(input,0,1);

    bool firstLetterIsVowel = true;

//see's if first letter is a vowel
    if ((firstLetter == "a") || (firstLetter == "e") || (firstLetter == "E") || (firstLetter == "i") || (firstLetter == "I") || (firstLetter == "o") || (firstLetter == "O") || (firstLetter == "u") || (firstLetter == "U"))
    {
        firstLetterIsVowel = true;
    }
    else
    {
        firstLetterIsVowel = false;
    }

//converts to pig latin
    if (firstLetterIsVowel == false)
    {
        output.erase(0,1);

        output.insert(length,firstLetter);

        output.insert(length + 1,"ay");
    }

    else if (firstLetterIsVowel == true)
    {
        output.insert((length) + 1,"way");
    }

    cout << output << endl;




    return 0;
}

究竟是什么问题?

4

1 回答 1

1

之后output.erase(0,1), 的长度outputlength-1。然后output.insert(length,firstLetter)指定超出范围的索引。

如果你想追加到字符串的末尾,有append方法。

于 2020-05-10T00:12:08.973 回答