2014-11-21 86 views
0

我想打开多个文本文件并将流存储为矢量。打开多个文本文件的流

#include <vector> 
#include <iostream> 
#include <string> 
#include <fstream> 
using namespace std; 

int main() 
{ 

vector<string> imgSet 
vector<ofstream> txtFiles; 

// . 
// . 

    for(int i=0 ; i<imgSet.size() ; i++) 
    { 
      ofstream s; 
      s.open(imgSet[i].getName(), std::ofstream::out); 
      txtFiles.push_back(s); 
    } 

} 

的getName样子:

const string& getName() const; 

我编译这个与G ++ ubuntu上,我不明白为什么我得到它的错误一长串。如何解决这个问题

+0

什么是'imgSet [i] .getName()'? 'std :: string'没有成员函数'getName()'。 – 2014-11-21 10:51:12

回答

2

在C++ 03中,std :: fstream中没有operator =或copy构造函数。 你可以这样做:

vector<ofstream*> txtFiles; 
//... 
for(int i=0 ; i<imgSet.size() ; i++) 
{ 
     txtFiles.push_back(new ofstream(imgSet[i].getName(), std::ofstream::out)); 
} 
+0

那么,我怎样才能实现创建多个文件的目标? – mkuse 2014-11-21 10:17:44

+0

@mkuse我添加了一个示例,您可以如何实现此目的。 – FunkyCat 2014-11-21 10:20:47

+0

似乎不起作用,只是在我的问题中为getName()添加了声明 – mkuse 2014-11-21 10:28:55

2

各种iostream类既不是可复制的,也不转让。在pre-C++ 11的 中,向量的元素必须都是。关于唯一的解决方案 是使用std::ofstream*(可能包装在一个类 确保适当的删除)的载体。

在C++ 11中,iostream类已被制作成可移动的,并且矢量 已被扩展以允许可移动成员。所以,你可以写的东西 像:

for (std::string const& fileName : imgSet) 
    txtFiles.emplace_back(fileName); 

此设或多或少C++ 11的支持;我不知道 g ++的状态,但是这不会与我使用的版本(4.8.3)一起传递。我认为 它比编译器更像是一个库的问题,它可能与 一起使用该库的更新版本。 (别忘了编译 和-std=c++11。)