怎样删除C/C++代码中的所有注释
3个回答
展开全部
这样就可以:
#include <iostream>
#include <fstream>
using namespace std;
void deleteComments(char *, int);
int main() {
string filename;
cout << "Please enter name for a cpp file:" << endl;
cin >> filename;
ifstream fin;
try {
fin.open(filename.c_str());
} catch(std::exception &e)
{
cout << e.what() << endl;
}
if (fin.is_open())
{
cout << "Open " << filename << " successfully!" << endl;
}
char buf[102400];
int n = fin.readsome(buf, sizeof(buf));//read(buf, sizeof(buf));
if (n == -1)
{
fin.close();
}
deleteComments(buf, n);
cout << "After Dealing: " << endl << buf <<endl;
return 0;
}
void deleteComments(char* buf, int n)
{
char *p, *end, c;
p = buf;
end = buf + n;
char *pos1 = NULL, *pos2 = NULL;
bool flag1 = false, flag2 = false;// " and '
int flag3 = 0, flag4 = 0, flag5 = 0;// for /*... //... */
while( p < end)
{
c = *p;
cout << "new char: " << c <<endl;
switch(c)
{
case '"':
{
if (flag3 == 0)
flag1 = (flag1 == true)?false:true;
p ++;
} break;
case '\'':
{
if (flag3 == 0)
flag2 = (flag2 == true)?false:true;
p ++;
} break;
case '/':
{
p ++;
if (*p == '/' && (flag3 == 0)) // ..... //....
{
p ++;
cout << "in // " << endl;
cout << " falg3: " << flag3 << " flag5: " << flag5 << " flag1: " << flag1 << " flag2: " << flag2 << endl;
if (!flag1 && !flag2 && (flag5 == 0) && (flag4 == 0) && (flag3 == 0))
{
//flag4 ++;
// deal with //...:delete char until '\n'
cout << "deal with // ..." << endl;
*(p-1) = ' ';
*(p-2) = ' ';
while (*p != '\n')
{
cout << "dealing : " << *p << " ";
*p = ' ';
p ++;
}
}
}
else if ( *p == '*' && !flag1 && !flag2 && (flag3 == 0)) // .... /*.....
{
p ++;
flag3 ++;
cout << " falg3: " << flag3 << " flag5: " << flag5 << " flag1: " << flag1 << " flag2: " << flag2 << endl;
if (!flag1 && !flag2 && (flag4 == 0) && (flag3 == 1))
{
pos1 = p;// delete from pos1
}
}
}break;
case '*':
{
p ++;
if (*p == '/' && !flag1 && !flag2) // .... */...
{
flag5 ++;
cout << " falg3: " << flag3 << " flag5: " << flag5 << " flag1: " << flag1 << " flag2: " << flag2 << endl;
if(!flag1 && !flag2 && (flag3 != 0) && (flag5 != 0))
{
flag3 = 0;
flag5 --;
pos2 = p - 2;
cout << "deal with \/* .. *\/" << endl;
// deal wtih /*... */... : delete from pos1 to pos2
char *pos = pos1;
*(pos - 1) = ' ';
*(pos - 2) = ' ';
*(pos2 + 1) = ' ';
*(pos2 + 2) = ' ';
do {
cout << "dealing: " << *pos << endl;
*pos = ' ';
pos ++;
} while(pos != pos2 + 1);
}
}
} break;
default:
p ++;
break;
}
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2019-05-19
展开全部
踱步狼注释清理 StrollingWolf 一键批量清理,我碰到的最好用的代码清理工具。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2017-07-30
展开全部
手动操作
~
~
~
~
~
~
~
~
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询