Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a C++ program to remove comments

Tags:

c++

parsing

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.

like image 800
Meir Avatar asked Aug 13 '26 04:08

Meir


1 Answers

UPDATE:

Someone else mentioned this, but I think get is 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.

like image 101
Scott Wisniewski Avatar answered Aug 15 '26 18:08

Scott Wisniewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!