我正在尝试打开多个文件来编译其中的数据。我的程序可以编译,但是当我运行它时出现以下错误:
terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted
到目前为止,我的程序非常冗长,所以我将只链接其中处理打开文件的部分。
int main(int argc,char *argv[])
{
vector<Plays> yearsEntered;
Plays *MyPlays = new Plays();
if (argc < 2)
{
cout << "No filenames given." << endl;
return 0;
}
for(int i=1;i < argc; ++i)
{
string filename = argv[i];
cout << filename << endl;
filename.append(".csv");
cout << filename << endl;
ifstream inputFile(filename.c_str(), ios::in);
inputFile.open(filename.c_str());
//Error checking in case file fails to open
if (!inputFile)
{
cout << "Could not open file. " <<
"Try entering another file." << endl;
}
}
我不太清楚为什么会出现错误,但如果我不得不猜测,我会说这与 argv[i] 是一个 *char 数组这一事实有关,我正在设置它等于一个字符串。此外,当我运行该程序时,它的运行方式如下:./Analyze 2009 2010(等)。当我运行它时,它会打印出我想要打开的文件的名称,所以我知道问题出在它试图打开文件本身时。这是我第一次提出问题,所以如果有任何我未能遵循的约定,请告诉我,我会尽力解决。
最佳答案
您已经打开过一次文件。您无需再次打开它们。
std::ifstream
构造函数打开每个文件,然后您无缘无故地调用 .open()
。删除 inputFile.open() 行。
改变这个:
ifstream inputFile(filename.c_str(), ios::in);
inputFile.open(filename.c_str());
对此:
ifstream inputFile(filename.c_str());
关于c++ - 尝试在 C++ 中打开多个文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18795442/