实现去除c语言注释的小工具
去除C代码中的注释,
1.单行注释//;
2.多行注释/**/;
3.单行注释以“\”结尾则下一行也为注释;
4.字符串中的注释不处理。
说是C语言,但其实所有C语系的都可以,比如Java。
小工具:去除C语言注释
#include<stdio.h>
intmain(intargc,char*argv[]){
enum{
literal,
single,
multiple,
string
}mode=literal;
charlast=0,current;
while((current=getchar())!=EOF){
switch(mode){
casesingle:{
if(last!="\\"&&(current=="\n"||current=="\r")){
putchar(current);
current=0;
mode=literal;
}
}break;
casemultiple:{
if(last=="*"&¤t=="/"){
current=0;
mode=literal;
}
}break;
casestring:{
if(last=="\\"){
putchar(last);
putchar(current);
}elseif(current!="\\"){
putchar(current);
if(current=="""){
mode=literal;
}
}
}break;
default:{
if(last=="/"){
if(current=="/"){
mode=single;
}elseif(current=="*"){
mode=multiple;
}else{
putchar(last);
putchar(current);
}
}elseif(current!="/"){
putchar(current);
if(current=="""){
mode=string;
}
}
}break;
}
last=current;
}
return0;
}
测试代码
#include<stdlib.h>
#include<stdio.h>
intmain(intargc,char*argv[])
{
//notshow\
notshow\
notshow
//notshow
/*notshow*/
intis;//notshow
int/*notshow*/ms;/*notshow*/
doubleds;//notshow\
notshow\
notshow
doubledm;/*...
notshow
notshow*/floatfs;/**
*nowshow
*/
float/**/fm;
charcs[]="aaa///***/";
charcm1[]=/*notshow*/"hello*/";
charcm2[]="/*redraiment"/*notshow*/;
/*printf("/////");*/
returnEXIT_SUCCESS;
}
处理后的代码
intmain(intargc,char*argv[]) intis;
#include<stdlib.h>
#include<stdio.h>
{
intms;
doubleds;
doubledm; floatfs;
floatfm;
charcs[]="aaa///***/";
charcm1[]="hello*/";
charcm2[]="/*redraiment";
returnEXIT_SUCCESS;
}相关文章