如何使用数组中的字符串打开文件

How do you open a file using a string from an array?

本文关键字:文件 字符串 何使用 数组      更新时间:2023-10-16

我有一个需要打开的文件名数组。当我放入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:…">

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

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