Daniel T. said:
Yes I definately think it's a good change.
You may be wondering at this point, why I picked that particular block
of code to extract into a seperate function. First, I noticed that there
were two variables that were only being used in that particular block of
code and not being used anywhere else in the program (includefile, and
includebuffer.) Second, when I asked you what that block of code did,
you were able to explain it with a simple phrase, one that translated
well into a function name.
Do you see any blocks of code where one or two variables are only being
used in that block and nowhere else? What would you say each block of
code is doing? Care to try turning one of them into a function?
In the mean time, let me introduce you to the 'else if' statement. It
will help make the main body of your code easier to read. Like this:
if (buffer == "")
{
outfile << " " << endl;
}
else if (buffer.substr(1,7) == "include")
{
string bestand = buffer.substr(9, (buffer.find_first_of("}") - 9));
bestand += ".tex";
insertFile( outfile, bestand );
}
else
{
outfile << buffer << endl;
}
See how this removes some of the odd nesting you had, without changing
the meaning of the code?[/QUOTE]
Ok, I made a new function (called bestand) that constructs the filename from
the line that contains "include". Maybe I should make a function that reads
all the lines of the configfile to an array? If I choose to add more
configuration parameters to the program later, I won't have to change that
part... Another question: do I really need the "const" before "string&"?
Thank you very much!
#include <string>
#include <fstream>
using namespace std;
void insertfile(ostream& os, const string& filename)
{
ifstream includefile(filename.c_str());
string includebuffer;
while (getline(includefile, includebuffer))
os << includebuffer << endl;
}
string bestand(const string& bufferline)
{
string firstpart = bufferline.substr(9, (bufferline.find_first_of("}") -
9));
firstpart += ".tex";
return firstpart;
}
int main()
{
string buffer;
string configin;
string configout;
ifstream config("config.txt");
getline(config, configin);
getline(config, configout);
config.close();
ifstream infile(configin.c_str());
ofstream outfile(configout.c_str());
while (getline(infile, buffer))
{
if (buffer == "")
{
outfile << " " << endl;
}
else if (buffer.substr(1,7) == "include")
{
insertfile(outfile, bestand(buffer));
}
else
{
outfile << buffer << endl;
}
}
infile.close();
outfile.close();
return 0;
}