簡體   English   中英

拋出'std :: out_of_range'what():basic_string :: substr的實例后調用終止

[英]terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr

我收到此錯誤: 從代碼中拋出“ std :: out_of_range'what():basic_string :: substr的實例后調用終止”

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>

using namespace std;

vector <string> n_cartelle;

ifstream in("n_cartelle.txt");
string linea;

while(getline(in,linea))
n_cartelle.push_back(linea);


for(int i=0; i < 4; ++i){


if(n_cartelle[i].substr(n_cartelle[i].size()-3) == "txt")
cout <<"si"<<endl;
else
cout<<"no"<<endl;

}

如果我嘗試這樣做:

if(n_cartelle[7].substr(n_cartelle[7].size()-3) == "txt")
cout <<"si "<<n_cartelle[7]<<endl;
else
cout<<"no"<<endl;

我沒有得到錯誤。

您所遇到的情況可能是main()脫離異常的情況,該異常終止了程序並給出了特定於操作系統的錯誤消息,如您所發布的錯誤消息。

首先,您可以在main()捕獲異常。 這將防止您的程序崩潰。

#include <exception>
#include <iostream>

int main()
{
    try
    {
        // do stuff
    }
    catch (std::exception const &exc)
    {
        std::cerr << "Exception caught " << exc.what() << "\n";
    }
    catch (...)
    {
        std::cerr << "Unknown exception caught\n";
    }
}

現在您已經有了此機制,實際上可以查找錯誤。

查看您的代碼, 可能n_cartelle元素少於4個,可能是n_cartelle.txt僅包含3行引起的。 這意味着n_cartelle[0]n_cartelle[1]n_cartelle[2]會很好,但是嘗試訪問n_cartelle[3]以及超出此范圍的任何東西都是不確定的行為,這基本上意味着任何事情都會發生。 因此,首先要確保n_cartelle實際上具有4個元素,並且您的程序已定義了行為。

接下來可能出錯的地方(老實說,很有可能是您的substr()調用)。 當您嘗試使用“不可能的”參數調用substr()時,例如,使子字符串從僅包含5個字符的字符串的字符10開始,則該行為是已定義的錯誤 -引發std::out_of_range異常。 當您不小心嘗試將負數作為substr()的第一個參數傳遞時,也會發生這種情況(幾乎每次都是間接發生substr() 由於std::string的內部工作原理,負數將轉換為巨大的正數,肯定比字符串長得多,並導致相同的std::out_of_range異常。

因此,如果您的一行內容的長度少於3個字符,則size() - 3為負數,而我剛才解釋的情況就發生了。

暫無
暫無

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

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