Removing comments from a file

Hi,

I'm an absolute newbie in C++ and want to do the following:

Remove all kinds of comment from a file.

I've already searched around a bit and found the following code on this site:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(void) {
    string source;
    ifstream readFile("input.cpp");
    getline(readFile, source, '\0');
    while(source.find('/*') != string::npos) {
        size_t Beg = source.find('/*');
        source.erase(Beg, (source.find('*/', Beg) - Beg)+2);
    }
    while(source.find("//") != string::npos) {
        size_t Beg = source.find("//");
        source.erase(Beg, source.find("\n", Beg) - Beg);
    }
    cout << source;
    return 0;
}


While the code above works fine in most cases it fails at codes like this:

1
2
3
4
5
6
7
8
9
#include <iostream>

const char c = "/*" ;

int main( )
{
    std::cout << "Will I still be here?" ;
    return 0;
}


1
2
3
4
// this is a single line comment, but it ends with an escape char:  \
  this line is also considered part of the comment \
  as is this one (even if the forum syntax highlighting doesn't show it)
this_is_not_a_comment();  


So basically I got the problem that my code isnt recognizing that the sign "//" or "/*" "*/" is part of a namedeclaration or string. I think that the solution should be somehow via if or switch in order to verify if // is a real comment or not, but I got no clue how to do this properly.
Could anyone help me?

Last edited on
Topic archived. No new replies allowed.