比较字符串

时间:2018-01-20 18:10:31

标签: c++ string exception std

我正在学习C ++,在这项任务中,我将学习有关C ++的各种错误。我在这段代码中识别并修复了两个先前的错误,但是在程序运行阶段抛出“std :: out_of_range”并关闭时发生的第三个错误。

该程序不是由我编写的,但它基本上是刽子手猜词 正确猜出最后一个字母时会发生异常。

整个代码的链接是https://onlinegdb.com/Hk-84-WSz,但相关内容发生在第100行和第106行,据我所知。

整个错误消息:

terminate called after throwing an instance of 'std::out_of_range'                                                                                                                  
what():  basic_string::at: __n (which is 1) >= this->size() (which is 1)                                                                                                          
Aborted  

以下是导致异常的函数:

bool onko_sana_jo_arvattu(std::string sala, std::string arvatut)
{

    for (std::string::size_type indeksi = 0; indeksi <= sala.size(); ++indeksi)
    {
    // The next line seems to be causing the exception when the last letter has been guessed
        if (arvatut.find(sala.at(indeksi)) == std::string::npos)
        {
            return false;
        }
    }

    std::cout << "stuff" << std::endl;
    return true;
}

2 个答案:

答案 0 :(得分:2)

indeksi <= sala.size()

必须是:

indeksi < sala.size()

std::string0索引到size - 1

答案 1 :(得分:0)

for (std::string::size_type indeksi = 0; indeksi <= sala.size(); ++indeksi)

更改为

for (std::string::size_type indeksi = 0; indeksi < sala.size(); ++indeksi)

从Discord找到解决方案(“编程讨论”)