簡體   English   中英

比較字符串中的符號時,std :: out_of_range錯誤

[英]std::out_of_range error when comparing symbols in strings

我正在學習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;
}
indeksi <= sala.size()

一定是:

indeksi < sala.size()

as std::string0size - 1索引。

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

變成

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

從Discord找到的解決方案(“編程討論”)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM