在抛出"std::out_of_range"实例后终止调用

terminate called after throwing an instance of 'std::out_of_range'

本文关键字:调用 实例 终止 range out std of      更新时间:2023-10-16

我基本上试图从不同的文件写入一些值到一个文本文件。

我得到我的输出打印在终端上,但它无法写入文件。给pfile写信有问题。否则这段代码可以正常工作。

#include<cstdio>
#include<cstdlib>
#include<fstream>
#include<string>
#include<cstring>
#include<iostream>
using namespace std;
int main()
{
    char word[20];
    ifstream ifile;
    ofstream pfile;
    string iline, event_id, event_id_modified, Event, pline,s;
    int found, i=1, c_word = 0, c_line =0;
    float comm_pos;
    ifile.open("tryrsvp.doclist",ios::in);
    pfile.open("polarityy.txt",ios::app);
    pfile<<"event_id"<<"t"<<"polarity"<<"n";
    while(!ifile.eof())
    {
    c_word =0;
    c_line =1;        
        ifstream dfile;
        getline(ifile,iline);
        found = iline.find('n');
        Event = iline.substr(15,iline.size()-4-15); 
        event_id = iline.substr(0,found-1);
            if(event_id.size()==0)
              break;
        event_id_modified = event_id;   
        event_id_modified.append("_auto_anns/exp_polarity.txt");
        char *distributed_file = new char[event_id_modified.size()+1];
        copy(event_id_modified.begin(), event_id_modified.end(), distributed_file);
        distributed_file[event_id_modified.size()] = '';
        dfile.open(distributed_file,ios::in); 
    strcpy(word,"positive");     
    while (dfile >> s)
    {
    if(s == word)
    ++ c_word;
    c_line++;
    }
    c_line=c_line/2;
    if(c_word==0)
    comm_pos = 0;
    else
    comm_pos = (float)(c_word)/(float)(c_line);
    cout<<event_id<<"t";
    cout<<c_word<<"t"<<c_line<<"t"<<comm_pos<<"n";
    pfile<<Event<<"t"<<comm_pos<<"n";
        dfile.close();
        delete[] distributed_file;
        if(ifile.eof())
            break;
    }
    pfile.close();
    ifile.close();
}

我得到这个错误

抛出'std::out_of_range'实例后终止调用

what():  basic_string::substr

Aborted (core dumps)

我没有尝试调试它,但乍一看这里可能有问题:

    Event = iline.substr(15,iline.size()-4-15);

基本上,在使用line.size()之前,您不会检查它是否> 15+4。因此,文件中任何比这短的行都将导致程序崩溃。

相同:

   event_id = iline.substr(0,found-1);

如果你的文件中碰巧有空行,你就会遇到麻烦。这是因为string::find()将返回string::npos。那么计算npos-1很可能无法按预期工作…

相关文章: