I’m trying to create a program that takes a text file of c++ code and outputs another
file with that code, minus any comments that it contains.
Assuming that rFile and wFile are defined as follows:
ifstream rFile; // File stream object for read only
ofstream wFile; // File stream object for write only
rFile.open("input.txt", ios::in);
wFile.open("output.txt", ios::out);
My first thought was simply go through the text and do the equivalent of pen-up(logo
reference) when a (slightly improved) peek() identifies /* and pen down when it sees */. Of course after
seeing // it would “pen-up” until it reaches \n.
The problem with this approach is that the output.txt doesn’t include any of the
original spaces or newlines.
This was the code (I didn’t even try removing comments at this stage):
while (!rFile.eof())
{
rFile>>first; //first is a char
wFile<<first;
}
So then I tried getting each line of code separately with getline() and then adding
an endl to the wFile. It works so far, but makes things so much more complicated, less
elegant and the code less readable.
So, I’m wondering if anyone out there has any pointers for me. (no pun intended!)
N.B. This is part of a larger homework assignment that I’ve been given and I’m
limited to using only C++ functions and not C ones.
UPDATE:
Someone else mentioned this, but I think
getis probably a better function to use, than “>>”.Original post:
The solution is to read the input character-by-character, rather than using
getline().You can read the characters in using “>>”, and output them using “<<“. That way you don’t have to use “endl” at all. The line terminator and space characters will be read in as individual characters.
When you see the start of a comment, you can then just stop outputting characters until you eat the appropriate comment terminator.
You also need to make sure to treat “\r\n” as a single terminator when processing the end of a “//” token.