How to remove comments from a string in C++

1 Answer

0 votes
#include <iostream>
#include <string>

std::string removeComments(const std::string& input) {
    std::string out;
    size_t i = 0;

    while (i < input.size()) {

        // Check for // single-line comment
        if (i + 1 < input.size() && input[i] == '/' && input[i + 1] == '/') {
            i += 2;
            while (i < input.size() && input[i] != '\n')
                i++;
        }

        // Check for /* ... */ block comment
        else if (i + 1 < input.size() && input[i] == '/' && input[i + 1] == '*') {
            i += 2;
            while (i + 1 < input.size() &&
                   !(input[i] == '*' && input[i + 1] == '/'))
                i++;
            if (i + 1 < input.size())
                i += 2; // skip closing */
        }

        // Normal character
        else {
            out.push_back(input[i]);
            i++;
        }
    }

    return out;
}

int main() {
    std::string text =
        "int x = 10; // single-line comment\n"
        "int y = 20; /* block comment */\n"
        "int z = x + y; /* multi\n"
        "line\n"
        "comment */ return z;";

    std::string cleaned = removeComments(text);

    std::cout << cleaned << "\n";
}


/* 
run:

int x = 10; 
int y = 20; 
int z = x + y;  return z;

*/

 



answered 1 day ago by avibootz
...