473,322 Members | 1,714 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

I managed to remove comments froma cpp file

The problem was to write a program that reads a .cpp file containing a C++ program and produces a file with all comments stripped from the program.

I finally got the answer.


Here it is if someone want it as no one could do it : P



#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void remove_comments ( ifstream& , ofstream& ); // Function declaration.

void main()
{
string infile, outfile; // declaration of the names of the stream files.
ifstream source; // declaration of the stream files.
ofstream target; // declaration of the stream files.


// To validate the user when entering the name of the file wrong.
do {

cout << "Enter Input File Name: ";
cin >> infile;

} while ( source.fail() );

cout << "Enter Output File Name: ";
cin >> outfile;

source.open ( infile.c_str() );
target.open ( outfile.c_str() );


remove_comments ( source , target); // Calling the function,





source.close(); // to close the opened files.
target.close();

}


//---------------------------------------------


// This function takes the two files from the main. It reads line by line from the input file and copy it to the output file eliminating the comments.
void remove_comments ( ifstream& Source , ofstream& Target)
{
string line;
bool flag = false;


while ( ! Source.eof() ) // This loop is to get assure that the whole input file is read.
{


getline(Source, line); // To read line by line.


if ( line.find("/*") < line.length() ) // searching for " /* " to eliminat it and all its content.
flag = true;
if ( ! flag )
{
for (int i = 0; i < line.length(); i++ )
{

if(i<line.length())
if ( ( line.at(i) == '/' ) && ( line.at(i + 1 ) == '/' ) ) // searching for " // " to eliminate all its content.
break;
else
Target << line[i]; // To copy lines in the output file.

}

Target<<endl;


}
if ( flag )
{ if ( line.find("*/") < line.length() )
flag = false;
}


}
}
Nov 13 '06 #1
1 8309
Very good.
I just enhanced it, because your programa was failing when you put "/*" as a string, so it was not a commentary and the program was treating it like commentary.

I organized it in classes to. Thanks.

----------------------------------------------------------------------------------------------------------
MAIN.CPP

/* Federal University of Minas Gerais - UFMG
Engineering School
Object Oriented Design, Project and Programming
Practical Work 2;part 1
Professor: Renato Mesquita
Group: Danilo Gomes
Bruno Damiao
*/
#include <iostream>
#include <fstream>
#include <string>
#include "FFiles.h"

using namespace std;

void main()
{ FFiles readFile;

string infile, outfile; //in and out file name
ifstream source; // declaration of the stream files.
ofstream target;
do{
cout << "Enter Input File Name: ";
cin >> infile;
}while(source.fail());//while file reading fails, keep asking for input file name

cout << "Enter Output File Name: ";
cin >> outfile;

source.open(infile.c_str());
target.open(outfile.c_str());

readFile.remove_comments(source, target); //Calling the function,

source.close();//to close the opened files.
target.close();

}

---------------------------------------------------------------------------------------------------------------
FFILES.H

//declaration of FFiles
#include <fstream>

using namespace std;

class FFiles{

public:

void remove_comments(ifstream&, ofstream&); // Function declaration.
void checkCommentsSlashSlash(string&, bool&, ofstream&);
void checkComments(string&, bool&, ofstream&);
};

------------------------------------------------------------------------------------------------------------------
FFILES.CPP

//Definition of FFiles
#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include "FFiles.h"

using namespace std;

void FFiles::checkCommentsSlashSlash(string& line, bool& flag, ofstream& Target)
{
if (!flag)
{
for(int i = 0; i < line.length(); ++i )
{
if((line.at(i) == '/') && (line.at(i+1) == '/')) // searching for " // " to eliminate all its content.
break;
else
Target << line[i]; // copy the character of the position i to the Target
}
Target << endl;
}
}//end FFiles::checkCommentsSlashSlash

void FFiles::checkComments(string& line, bool& flag, ofstream& Target)
{
int contaAspas = 1; //initialized as 1, because if don't find "/*" will not set flag true
if (line.find("/*") < line.length()) // searching for " /* " to eliminate it and all its content.
//the .find searchs in the forward direction for the first occurrence of a substring that matches
//the specified sequence of characters and returns its position
{
contaAspas = 0;
for(int i = 0; i < line.find("/*"); ++i ){ //check if "/*" is or isn't a commentary
if((line.at(i) == '"'))
contaAspas++;
}
}
if((contaAspas % 2) == 0) //in case of even quotation marks it's a commentary
flag = true;

checkCommentsSlashSlash(line, flag, Target); //check the "//" comments

if (flag)
{
if (line.find("*/") < line.length()) //when it finds the end of commentary, it restarts to copy
flag = false;
}
}//end FFiles::checkComments


void FFiles::remove_comments (ifstream& Source ,ofstream& Target)
{
string line; //auxiliar string to store the read line
bool flag = false;

while (!Source.eof()) // This loop is to get assure that the whole input file is read.
{
getline(Source, line); // To read line by line.
//checks comments for the read line
checkComments(line, flag, Target);

}//end while
}//end FFiles::remove_comments

-----------------------------------------------------------------------------------------------------------

Hope it be helpful!
Oct 3 '08 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Jacob Cohen | last post by:
Under VC7.1, I am trying to wrap a native-C++ DLL that contains C++ objects in a Managed-C++ class library for use in a C# project. I created and compiled the native DLL under VC7.1 as a Win32...
1
by: peelman | last post by:
For some reason this is not working for me. How to remove all newline characters from a string? I have tried: myString.Replace ("\n", ""); I have also tried using TrimStart and TrimEnd...
100
by: jacob navia | last post by:
Recently, a heated debate started because of poor mr heathfield was unable to compile a program with // comments. Here is a utility for him, so that he can (at last) compile my programs :-) ...
12
by: Cmtk Software | last post by:
I'm trying to define an enum which will be used from unmanaged c++, C++/CLI managed c++ and from C#. I defined the following enum in a VS dll project set to be compiled with the /clr switch: ...
2
by: nzrusty | last post by:
Im trying to read froma file, and then work out the values of the table, i.e. the sum of x. the file i am reading from is as follows: x y 1.0 2.876 2.6 4.234 3.7 8.874 4.5 7.698 6.0 9.932 ...
9
by: Frank Potter | last post by:
I only want to remove the comments which begin with "//". I did like this, but it doesn't work. r=re.compile(ur"//+$", re.UNICODE|re.VERBOSE) f=file.open("mycpp.cpp","r") f=unicode(f,"utf8")...
0
by: ITAJP | last post by:
I'm using a Managed C++ dll called froma a VB program. I'm trying to use argument by ref in the Dll functions, but in the Dll manifest the functions still appear with arguments by val. I use...
1
by: =?Utf-8?B?QmlsbHkgWmhhbmc=?= | last post by:
Is this a managed post?
61
by: arnuld | last post by:
I have created a program which creates and renames files. I have described everything in comments. All I have is the cod-duplication. function like fopen, sprint and fwrite are being called again...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.