【问题标题】:opening file from string array variables [duplicate]从字符串数组变量打开文件[重复]
【发布时间】:2015-03-23 21:29:58
【问题描述】:

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

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&lt;char,char_traits&lt;char&gt;&gt;::open(files[i])

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

有什么想法吗?

【问题讨论】:

    标签: c++ ifstream


    【解决方案1】:

    “我的编译器说:”
    Can't call basic_ifstream&gt;::open(files[i]) in current scope.

    旧的C++标准版本(C++11之前)想看const char*函数的const char*参数,可以直接用

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

    保持您的代码向后兼容。

    【讨论】:

    • @Arland 请注意,通常要求重复并没有什么坏处,它们可以帮助其他研究人员找到解决问题的正确方法。如果您认为这个答案解决了您的问题,您仍然可以接受。
    猜你喜欢
    • 1970-01-01
    • 2018-05-09
    • 2019-04-11
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    相关资源
    最近更新 更多