还是喜欢这个有限状态机的写法,又简单,又明了!话不多说,自己根据程序画一个状态机自己看吧。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <stdio.h> 2 #include <string.h> 3 #include <cstdlib> 4 5 void initialize_fsm(char fsm[7][256]); 6 7 int main() 8 { 9 int ch, temp = 0; 10 int state = 0; 11 char fsm[7][256]; 12 13 FILE *pfin; 14 if((pfin = fopen("sweep-comments.txt", "r")) == NULL){ 15 printf("cannnot open the file"); 16 exit(0); 17 } 18 19 FILE *pfout; 20 pfout = fopen("result.txt", "w"); 21 initialize_fsm(fsm); 22 23 while((ch = fgetc(pfin)) != EOF){ 24 state = fsm[state][ch]; 25 temp = ch; 26 switch(state){ 27 case 5: 28 case 6: 29 case 0: 30 fputc(ch, pfout); 31 break; 32 case 7: 33 state = 0; 34 break; 35 } 36 } 37 return 0; 38 } 39 void initialize_fsm(char fsm[7][256]) 40 { 41 int lenth = sizeof(char) * 256; 42 memset(fsm[0], 0, lenth); 43 memset(fsm[1], 0, lenth); 44 memset(fsm[2], 2, lenth); 45 memset(fsm[3], 3, lenth); 46 memset(fsm[4], 3, lenth); 47 memset(fsm[5], 5, lenth); 48 memset(fsm[6], 5, lenth); 49 50 fsm[0]['"'] = 5; 51 fsm[0]['/'] = 1; 52 fsm[1]['/'] = 2; 53 fsm[1]['*'] = 3; 54 fsm[2]['\n'] = 7; 55 fsm[3]['*'] = 4; 56 fsm[4]['/'] = 7; 57 fsm[5]['\\'] = 6; 58 fsm[5]['"'] = 0; 59 }