从字符串数组变量打开文件

opening file from string array variables

我正在尝试编写一个循环访问多个文件的程序。

string files[]={"file1.txt","file2.txt"};
int i=0;
ifstream fin;
while(i<2){
    fin.open(files[i]);
    fin.close();
    i++;
}

这是我的代码的精简版。我从 fin.open 行收到错误。我的编译器说:无法在当前范围内调用 basic_ifstream<char,char_traits<char>>::open(files[i])

如果我输入实际的字符串,它工作正常。 fin.open("file1.txt"),但我想避免复制出相同的代码块 8 次。

有什么想法吗?

" My complier says:"
Can't call basic_ifstream>::open(files[i]) in current scope.

较旧的 C++ 标准版本(C++11 之前)想要查看 std::ifstream::open() 函数的 const char* 参数,您可以使用

fin.open(files[i].c_str()); 

让您的代码向后兼容。