您的位置:首页 > 编程语言 > C语言/C++

去掉C/C++程序中的注释

2012-09-12 15:16 183 查看
还是喜欢这个有限状态机的写法,又简单,又明了!话不多说,自己根据程序画一个状态机自己看吧。

View Code

#include <stdio.h>
#include <string.h>
#include <cstdlib>

void initialize_fsm(char fsm[7][256]);

int main()
{
int ch, temp = 0;
int state = 0;
char fsm[7][256];

FILE *pfin;
if((pfin = fopen("sweep-comments.txt", "r")) == NULL){
printf("cannnot open the file");
exit(0);
}

FILE *pfout;
pfout = fopen("result.txt", "w");
initialize_fsm(fsm);

while((ch = fgetc(pfin)) != EOF){
state = fsm[state][ch];
temp = ch;
switch(state){
case 5:
case 6:
case 0:
fputc(ch, pfout);
break;
case 7:
state = 0;
break;
}
}
return 0;
}
void initialize_fsm(char fsm[7][256])
{
int lenth = sizeof(char) * 256;
memset(fsm[0], 0, lenth);
memset(fsm[1], 0, lenth);
memset(fsm[2], 2, lenth);
memset(fsm[3], 3, lenth);
memset(fsm[4], 3, lenth);
memset(fsm[5], 5, lenth);
memset(fsm[6], 5, lenth);

fsm[0]['"'] = 5;
fsm[0]['/'] = 1;
fsm[1]['/'] = 2;
fsm[1]['*'] = 3;
fsm[2]['\n'] = 7;
fsm[3]['*'] = 4;
fsm[4]['/'] = 7;
fsm[5]['\\'] = 6;
fsm[5]['"'] = 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: