【问题标题】:How do you open a file using a string from an array?如何使用数组中的字符串打开文件?
【发布时间】:2020-03-02 10:34:57
【问题描述】:

我有一个需要打开的文件名数组。当我把plans.open。它给了我错误“没有匹配函数调用 'std::basic_ifstream::open(std::__cxx11:...”

#include <iostream>
#include <fstream>
#include <cstring>
#include <string>

using namespace std;

int main(){
    ifstream files;
    ifstream plans;
    string stufiles[100];
    int numFiles,timeBlocks;
    files.open("filesToProcess.txt");
    if (files.fail()){ //checks to see if the selected store file opened
        cout << "Error when opening file!" << endl;
        return 0;
    }
    files >> numFiles;
    for (int i= 0; i<= numFiles; i++) {
         files >> stufiles[i];
    }
    files.close();
    cout << stufiles[0] << endl;
    plans.open(stufiles[0]);
    if (plans.fail()){ //checks to see if the selected store file opened
        cout << "Error when opening file!" << endl;
        return 0;
    }
}

这应该使用数组中的文件名打开文件。 它给了我错误“没有匹配函数调用 'std::basic_ifstream::open(std::__cxx11:...”

【问题讨论】:

  • plans.open(stufiles[0].c_str());
  • for (int i= 0; i&lt;= numFiles; i++) { files &gt;&gt; stufiles[i]; -- 当i == numFiles时覆盖内存。
  • @PaulMcKenzie 仅当numFiles &gt;= 100
  • 循环应该使用&lt;而不是&lt;=

标签: c++ arrays file


【解决方案1】:

您的编译器版本的std::ifstream::open() 不支持std::string 作为输入,因此您必须给它一个const char*。您可以为此使用std::string::c_str()

plans.open(stufiles[0].c_str());

【讨论】:

  • 我现在已经把它改成了你说的,现在我的代码编译并运行了;但是,现在当我运行它时,文件无法打开。这些文件位于同一目录中。
  • @CurtFitz 你确认numFiles > 0了吗?您是否确认 stufiles[0] 包含您所期望的内容?如果您使用相对路径打开文件,您是否确认您的程序的工作目录是您所期望的?这些是基本的调试步骤。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-28
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多