抛出'std :: out_of_range'的实例后调用terminate():basic_string :: substr

iny*_*ind 1 c++ 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;

}
Run Code Online (Sandbox Code Playgroud)

如果我尝试这个:

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

我没有得到错误.

Chr*_*ckl 13

您遇到的情况可能是异常下降的情况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";
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你已经有了这个机制,你可以实际找到错误.

查看您的代码,可能只有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().由于a的内部工作原理std::string,负数将转换为一个巨大的正数,肯定比字符串长得多,并导致相同的std::out_of_range异常.

所以,如果你的一条线的长度小于3个字符,size() - 3则为负,我刚才解释的是.