nom_nutella
nom_nutella

Reputation: 171

Removing comments from C++ string

I am trying to do a project that removes the comments from a previously written program. From what I have in theory it should work I think, but for some reason the output file is always empty in the end... Please help in any way you can... (P.S. Sorry if the indents are sloppy, copy and pasting never seems to work out well for me)

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

using namespace std; 


void comment_destroyer(ifstream&,ofstream&); 


int main (void) {


string filestart;  
string fileend;    
ifstream start;    
ofstream end;      


do {
    cout<<"Name of the file you want to remove comments from: ";
    cin >> filestart;
}  
while ( start.fail() );
cout << "What is the name of the file you want to call the stripped code?: ";
cin >> fileend; 

start.open ( filestart.c_str() );
end.open ( fileend.c_str() );

comment_destroyer (start, end);

start.close();
end.close();

return 0;
  }

// 
//Start of functions
//

void comment_destroyer(ifstream& start, ofstream& end){
    string line; 
    bool found = false;
    int i=0;

    while (! start.eof()){
        getline(start,line); 

        if (line.find("/*")<line.length())
        found = true;
        if (!found){
            for (int i=0;i<line.length();i++)
                {
                    if(i<line.length())
                    if ((line.at(i)=='/') && (line.at(i+1)=='/'))
                    break;
                    else
                    end<<line[i];
                }

        end<<endl;

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

Upvotes: 1

Views: 801

Answers (2)

Blaz Bratanic
Blaz Bratanic

Reputation: 2279

The following section is erroneous. Instead of assigning false to found you use equality operator.

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

Change == to =

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

Upvotes: 2

Chris
Chris

Reputation: 1558

I think yur condition is wrong. string.find returns std::string::npos if the searched term was not found. According to npos this is -1, so the expression

 if (line.find("/*")<line.length())
    found = true;

always sets found to true.

Upvotes: 1

Related Questions