【问题标题】:std::out_of_range error when comparing symbols in strings比较字符串中的符号时出现 std::out_of_range 错误
【发布时间】:2018-01-20 18:10:30
【问题描述】:

我正在学习 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;
}

【问题讨论】:

    标签: c++ string exception std


    【解决方案1】:
    indeksi <= sala.size()
    

    必须是:

    indeksi < sala.size()
    

    因为std::string 的索引是从0size - 1

    【讨论】:

    • 是的,刚刚从 Discord 得到了相同的答案。有点惊讶的是,即使我没有“看到”它,我什至错过了尝试这样的事情。谢谢
    【解决方案2】:
    for (std::string::size_type indeksi = 0; indeksi <= sala.size(); ++indeksi)
    

    改为

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多