如何从给定的C/C++程序中删除注释()

给定一个C/C++程序, 从其中删除注释。
强烈建议最小化你的浏览器, 然后自己尝试。
这个想法是要维护两个标志变量, 一个指示启动单行注释, 另一个指示启动多行注释。设置标记后, 我们将查找注释的结尾, 并忽略开始和结尾之间的所有字符。
以下是上述想法的C++实现。

//C++ program to remove comments from a C/C++ program #include < iostream> using namespace std; string removeComments(string prgm) { int n = prgm.length(); string res; //Flags to indicate that single line and multpile line comments //have started or not. bool s_cmt = false ; bool m_cmt = false ; //Traverse the given program for ( int i=0; i< n; i++) { //If single line comment flag is on, then check for end of it if (s_cmt == true & & prgm[i] == '\n' ) s_cmt = false ; //If multiple line comment is on, then check for end of it else if(m_cmt == true & & prgm[i] == '*' & & prgm[i+1] == '/' ) m_cmt = false , i++; //If this character is in a comment, ignore it else if (s_cmt || m_cmt) continue ; //Check for beginning of comments and set the approproate flags else if (prgm[i] == '/' & & prgm[i+1] == '/' ) s_cmt = true , i++; else if (prgm[i] == '/' & & prgm[i+1] == '*' ) m_cmt = true , i++; //If current character is a non-comment character, append it to res elseres += prgm[i]; } return res; }//Driver program to test above functions int main() { string prgm = "/* Test program */\n" "int main()\n" "{\n" "//variable declaration \n" "int a, b, c; \n" "/* This is a test\n" "multiline\n" "comment for\n" "testing */\n" "a = b + c; \n" "}\n" ; cout < < "Given Program \n" ; cout < < prgm < < endl; cout < < " Modified Program " ; cout < < removeComments(prgm); return 0; }

输出如下
Given Program /* Test program */ int main() { //variable declaration int a, b, c; /* This is a test multiline comment for testing */ a = b + c; } Modified Program int main() { int a, b, c; a = b + c; }

本文由Sachin Gupta提供。如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请发表评论。
【如何从给定的C/C++程序中删除注释()】被认为是行业中最受欢迎的技能之一, 我们拥有自己的编码基础C++ STL通过激烈的问题解决过程来训练和掌握这些概念。

    推荐阅读