suppose I have a file like below and I would like to create 3 output files based on my first field .. .i.e, 1 /2/3.
Thats means 3 lines will go to the three files
1 AAAAAA BBBBBB CCCCC
2 DDDDDD EEEEEE FFFFF
3 GGGGGG HHHHHH IIIII
2 copy paste insert
1 andrew mathew horto
I expect something like this to happen
file1:-
1 AAAAAA BBBBBB CCCCC
1 andrew mathew horto
file2:-
2 DDDDDD EEEEEE FFFFF
2 copy paste insert
file3:-
3 GGGGGG HHHHHH IIIII
Here is my code so far but I am not able to create file dynamically. I mean here I am predefining the file names.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void parseFile(string file, string line)
{
ofstream out(file.c_str(),ios::app);
out<<line<<endl;
out.close();
}
int main()
{
ifstream in("inputfile.txt");
string line = "";
int count = 0;
while(getline(in,line))
{
string file = "file";
count++;
switch (count)
{
case 1:
parseFile("file1.txt",line); break;
case 2:
parseFile("file2.txt",line); break;
case 3:
parseFile("file3.txt",line); break;
case 4:
parseFile("file2.txt",line); break;
case 5:
parseFile("file1.txt",line); break;
}
}
cin.ignore();
cin.get();
return 0;
}
I want to automate the process. Like running a for loop and creating files on the run. Maybe like I will store the first field in a map and then create the files using for loop...
How can I do that ? Never done it before.
Thanks