在抛出"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()] = ' ';
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很可能无法按预期工作…
相关文章:
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 对象实例化调用构造函数的次数太多
- 如果 std::vector::clear() 不是静态的,如何在没有实例的情况下调用它?
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- C++应用程序 MySQL odbc 数据库连接错误:在引发"otl_tmpl_exception<>"实例后终止调用
- C++中的单例实现在调用 getInstance 函数时不会产生相同的类实例
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 在抛出 'std::runtime_error' 的实例后终止调用 what(): Filebuf 和 ostream 的 I/O 错误
- 从基类实例调用派生类方法而不进行强制转换
- 以下代码如何工作以每次为唯一调用堆栈唯一实例化模板函数?
- 在字符串函数中抛出'char const*'实例后调用的终止
- 如何使用 c++ 从另一个 cpp 文件中的 main.cpp 调用实例化类
- 统一功能使用模板专业化和接口来调用实例和原始类型
- 调用实例化函数时发生链接器错误
- 正在销毁调用实例
- 为什么我可以静态地调用实例函数