为什么我在抛出"错误异常"实例后调用错误终止

  • 本文关键字:错误 实例 异常 终止 调用 c++
  • 更新时间 :
  • 英文 :


我试图获取向量中的所有值,但每当我运行此代码时,它都会给我一个错误异常,我不知道错误在哪里。

对于所有询问vector.h的人来说,它是斯坦福德图书馆的一部分

这是我使用的txtfile

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <algorithm>
#include "vector.h"  //You can also use #include <vector>
using namespace std;

Vector<string> split(string str, string token) //The saving grace
{
Vector<string> result;
while(str.size()){
int index = str.find(token);
if(index!=string::npos){
result.push_back(str.substr(0,index));
str = str.substr(index+token.size());
if(str.size()==0)result.push_back(str);
}
else
{
result.push_back(str);
str = "";
}
}
return result;
}
bool isInteger(string str)
{
for(int i = 0; i<str.length(); i++)
{
if(isdigit(str[i]) == true)
{
return true;
}
}
return false;
}
//----------------------------------------------------//
//Lets get the text of the file into vectors
Vector<string> movieTitle(string txtfile)
{
Vector<string> text; //Contains all of the text
Vector<string> films; //All the films
fstream myFile;
string word;
myFile.open(txtfile);
if(!myFile.good())
{
cout << "ERROR: FILE NOT FOUND" << endl;
exit(1);
}
while(getline(myFile, word, 'n'))
{
//cout << word << endl;
text += split(word, "t");
}
for(int i = 0; text.size(); i++)
{
if(text[i].find("(") != string::npos && isInteger(text[i]))
{
films.push_back(text[i]);
}
}
return films;
}
int main()
{
Vector<string> test;
test = movieTitle("movies_mpaa.txt");
cout << test << endl;
return 0;
}

输出:在引发"ErrorException"实例后调用terminatewhat((:
中止(核心转储(

我只是对错误发生的地方感到困惑。

这是您的错误:

for(int i = 0; text.size(); i++)
{
if(text[i].find("(") != string::npos && isInteger(text[i]))

因为循环不能这样工作,所以第二个表达式是一个布尔表达式,它在进入循环体之前根据true进行检查。Stanford库类Vector::operator []的作用与std::vector的作用相同,如果i大于size()-1,则抛出异常。循环永远不会停止,因为如果size()一开始不是0,它永远不会返回0,所以最终i会变得更大。循环应该看起来像

for(int i = 0; i < text.size(); i++)

若您在程序停止后在GDB中使用backtrace命令,您会看到被调用的函数链导致灾难性的停止。您可以使用命令frame <number>找到您的代码,其中<number>将是该列表中的一项。GDB有大量的在线文档和常见问题解答,有上帝的指导如何使用它。

最新更新