尝试在 c ++ 中打开多个文件时出错

Error when trying to open multiple files in c ++

本文关键字:文件 出错      更新时间:2023-10-16

我正在尝试打开多个文件来编译其中的数据。我的程序编译,但当我运行它时,我收到以下错误:

在抛出"std::bad_alloc"实例后终止调用 什么(): 标准::bad_alloc 中止

到目前为止,我的程序相当长,所以我只链接其中处理打开文件的部分。

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