簡體   English   中英

拋出'std :: out_of_range'實例后調用終止

[英]terminate called after throwing an instance of 'std::out_of_range'

我基本上是試圖將不同文件中的某些值寫入文本文件。

我正在終端上打印輸出,但是無法將其寫入文件。 寫入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()] = '\0';

        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 

中止(核心已棄用)

我沒有嘗試調試它,但乍看之下這里可能存在問題:

    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可能無法按預期工作...

暫無
暫無

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

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