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;
}
}
}