So I need some ideas on how nicely parse a text file in C++. The files that I am parsing have the following format :
Command_A list of arguments
Command_B list of arguments
etc etc
Right now I am using an ifstream to open up the file and then I have this super long series of if-else statements to determine what to do for each type of command. This is proving to be a bit unwieldy (especially since some of the commands are for parsing other files...so I have nested if-elses with multiple ifstreams for the different files).
I was looking for another way of doing this but am not really sure what is the best approach. I was thinking about using a std::map where the keys are the command strings and the values are the function pointers but I am not familiar with storing function pointers in a map (especially if the different functions are of different return types, etc).
Below is basically what I am currently doing. I loop through the file and use "getline" to get the current line. Then I use a stringstream to parse the command. Then I use a very long list of if-elses to determine which function to call. Each line in the file also comes with a list of arguments so I use the stringstream to parse those and then pass those parameters into the function I call.
The problem here is two-fold
1) I have a very very large number of if-elses (around 50)
2) Some of the commands require me to parse new files and thus I have to open up another ifstream within the current ifstream. (see command_c)
So I'm looking for an easier/more efficient/prettier looking way to do this.
/*Open file and verify validity*/
std::ifstream parseFile(filename.c_str());
if(!parseFile.good())
{
cerr<<"ERROR: File is either corrupt or does not exist."<<endl;
exit(1); //Terminate program
}
//Loop over file line by line
std::string line;
while(!parseFile.eof())
{
std::getline(parseFile, line);
std::stringstream ss;
std::string command;
ss.str(line);
ss >> command;
if(command == "COMMAND_A")
{
float x,y,z;
ss >> x >> y >> z;
FunctionA(x,y,z);
}
else if(command == "COMMAND_B")
{
float a,b,c,d,e,f;
ss >> a >> b >> c >> d >> e >> f;
FunctionB(a,b,c,d,e,f);
}
else if(command == "Command_C")
{
string nextFile;
ss >> nextFile;
ParseFile(nextFile); //This is not recursive...this is another function
}
else if(...)
{
...
}
// etc, etc (this continues on for a long time)
}
parseFile.close();