0

I am basically trying to write some values from different files to a text file.

I am getting my output printed on the terminal but its unable to write to a file. There is a problem in writing to pfile. Otherwise this code works fine.

#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();

}

I am getting this error

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

what():  basic_string::substr

Aborted (core dumped)

Praetorian
  • 106,671
  • 19
  • 240
  • 328
MEH
  • 41
  • 1
  • 6

1 Answers1

0

I didn't try to debug it but at first glance there may be a problem here:

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

Basically you don't check that line.size() is > 15+4 before using it. So, any line in the file that are shorter than that will make your program crash.

Same here:

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

If you happen to have empty lines in your file, you'll be in trouble here. That is because string::find() will return string::npos. Then calculating npos-1 will likely not work as intended...

Guillaume
  • 91
  • 4