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

opening file from string array variables

本文关键字:文件 变量 字符串 数组      更新时间:2023-10-16

我正在尝试编写一个程序,该程序将遍历多个文件。

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次。

有什么想法吗?

"我的同谋说:"
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()); 

以保持代码向后兼容。