我写了一个英语到猪拉丁语的转换器,即使它正确地编译,它说它终止后,它抛出一个'std::out of range'的实例。

我正在做一个英语到猪拉丁语的转换器,作为一个学习基础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;
}

到底是什么问题?

解决方案:

output.erase(0,1),长度为 outputlength-1. 那么 output.insert(length,firstLetter) 指定一个越界的索引。

如果你想追加到字符串的末尾,可以使用 append 方法。

本文来自投稿,不代表实战宝典立场,如若转载,请注明出处:https://www.shizhanbaodian.com/40530.html

(0)
上一篇 20小时前
下一篇 20小时前

相关推荐

发表评论

登录后才能评论