File Card Processing in C ++

I need to write to a bunch of files at the same time, so I decided to use map <string, ofstream> .

 map<string, ofstream> MyFileMap; 

I take a vector<string> FileInd , which consists of, say, "a" "b" "c" , and try to open my files with

 for (vector<string>::iterator it = FileInd.begin(); iter != FileInd.end(); ++it){ ... MyFileMap[*it].open("/myhomefolder/"+(*it)+"."); } 

I get an error

 request for member 'open' in ..... , which is of non-class type 'std::ofstream*' 

I tried to switch to

 map<string, ofstream*> MyFileMap; 

But that didn't work either.

Can anyone help?

Thanks.

Clarification:

I tried both

map<string, ofstream> MyFileMap; map<string, ofstream*> MyFileMap;

with both

.open ->open

none of the 4 options work.

Solution (proposed in Rob code below):

Basically, I forgot the β€œnew”, the following works for me:

 map<string, ofstream*> MyFileMap; MyFileMap[*it] = new ofstream("/myhomefolder/"+(*it)+"."); 
+6
source share
1 answer

std::map<std::string, std::ofstream> cannot work, because std::map requires its data type to be Assignable, and std::ofstream not. Alternatively, the data type should be a pointer to a stream β€” either a raw pointer or a smart pointer.

Here's how I would do it using the power of C ++ 11:

 #include <string> #include <map> #include <fstream> #include <iostream> #include <vector> int main (int ac, char **av) { // Convenient access to argument array std::vector<std::string> fileNames(av+1, av+ac); // If I were smart, this would be std::shared_ptr or something std::map<std::string, std::ofstream*> fileMap; // Open all of the files for(auto& fileName : fileNames) { fileMap[fileName] = new std::ofstream("/tmp/xxx/"+fileName+".txt"); if(!fileMap[fileName] || !*fileMap[fileName]) perror(fileName.c_str()); } // Write some data to all of the files for(auto& pair : fileMap) { *pair.second << "Hello, world\n"; } // Close all of the files // If I had used std::shared_ptr, I could skip this step for(auto& pair : fileMap) { delete pair.second; pair.second = 0; } } 

and verse 2, in C ++ 03:

 #include <string> #include <map> #include <fstream> #include <iostream> #include <vector> int main (int ac, char **av) { typedef std::map<std::string, std::ofstream*> Map; typedef Map::iterator Iterator; Map fileMap; // Open all of the files std::string xxx("/tmp/xxx/"); while(av++,--ac) { fileMap[*av] = new std::ofstream( (xxx+*av+".txt").c_str() ); if(!fileMap[*av] || !*fileMap[*av]) perror(*av); } // Write some data to all of the files for(Iterator it = fileMap.begin(); it != fileMap.end(); ++it) { *(it->second) << "Hello, world\n"; } // Close all of the files for(Iterator it = fileMap.begin(); it != fileMap.end(); ++it) { delete it->second; it->second = 0; } } 
+8
source

Source: https://habr.com/ru/post/907630/


All Articles