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

标签 c++ file vector

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

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/

相关文章:

c++ - 如何从二进制文件中读取 double 并将其保存在 vector 中

c++ - 错误 : reference to overloaded function could not be resolved; did you mean to call it?

c++ - 避免/usr/include/boost

c++ - 将 child map 存储在基类 vector 中

使用 BufferedInputStream 读取大文件时 Java 文件 IO 被截断

语音处理中的矢量量化解说

c++ - 将 unique_ptr 作为对插入 vector 中

c++ - volatile 数据成员是否可以轻松复制?

java - 我正在尝试使用 Java 重命名文件,但由于某种原因它不起作用

linux - Unix 文件中的换行符