抛出'std :: out_of_range'

时间:2015-05-28 16:14:35

标签: c++

我基本上是尝试将不同文件中的某些值写入文本文件。

我在终端上打印输出但是无法写入文件。撰写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
     

中止(核心倾销)

1 个答案:

答案 0 :(得分:0)

我没有尝试调试它,但乍一看可能会出现问题:

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

基本上你不检查line.size()是否&gt;使用前15 + 4。 因此,文件中任何比这短的行都会使程序崩溃。

同样在这里:

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

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

相关问题