我正在开发一个英语到猪拉丁语转换器,作为一个学习基本 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;
}
究竟是什么问题?