在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
可将其分为下面四个状态进行讨论即可: 1 #include<stdio.h> 2 #include<windows.h> 3 #define INPUTFILE "input.c" 4 #define OUTPUTFILE "output.c" 5 6 enum Status{ 7 NULLSTATUS, 8 CPPSTATUS, 9 CSTATUS, 10 EOFSTATUS, 11 }; 12 int status = NULLSTATUS; 13 14 void do_null_status(FILE *ifp,FILE *ofp){ // 初始态为普通状态 (没有参与注释部分的内容 ) 15 int c1=fgetc(ifp); 16 switch(c1){ 17 case '/':{ 18 int c2 = getc(ifp); 19 switch(c2){ // .../* 20 case '*': 21 fputc('/',ofp); 22 fputc('/',ofp); 23 status = CSTATUS; 24 break; 25 case '/': // ... // 26 fputc('/',ofp); 27 fputc('/',ofp); 28 status = CPPSTATUS; 29 break; 30 case EOF: 31 fputc('/',ofp); 32 status = EOFSTATUS; 33 break; 34 default: // .../ ... 35 fputc('/',ofp); 36 fputc(c2,ofp); 37 break; 38 } 39 break; 40 } 41 case EOF: 42 status = EOFSTATUS; 43 break; 44 default: 45 fputc(c1,ofp); 46 break; 47 } 48 } 49 void do_cpp_status(FILE *ifp,FILE *ofp){ // 已进入C++风格注释(// ...) 保持此种风格注释 50 int c = fgetc(ifp); 51 switch (c) { 52 case '\n' : // ....\n 53 fputc('\n',ofp); 54 status = NULLSTATUS; 55 break; 56 case EOF : 57 status = EOFSTATUS; 58 break; 59 default: 60 fputc(c, ofp); 61 break; 62 } 63 } 64 void do_c_status(FILE *ifp,FILE *ofp){ // 进入C风格注释 ( /* ...) 目的改为C++风格注释 65 int c1= fgetc(ifp); 66 switch(c1) 67 { 68 case '*':{ 69 int c2= fgetc(ifp); 70 switch(c2){ 71 case '/' : // //...*/... 72 fputc('\n' ,ofp); 73 status = NULLSTATUS; 74 break; 75 case EOF: 76 fputc('*' ,ofp); 77 status = EOFSTATUS; 78 default: 79 fputc('*',ofp); 80 ungetc(c2, ifp); //这个地方调了好多遍才注意到,实在是愚钝。 81 break; 82 } 83 break; 84 } 85 case '\n': // /* ... \n 86 fputc('\n', ofp); 87 fputc('/' , ofp); 88 fputc('/' , ofp); 89 break; 90 case EOF: 91 status= EOFSTATUS; 92 break; 93 default: // /* ... 94 fputc(c1,ofp); 95 break; 96 } 97 } 98 void convert_work(FILE *ifp,FILE *ofp){ 99 while( status != EOFSTATUS){ 100 switch(status){ 101 case NULLSTATUS : 102 do_null_status(ifp,ofp); 103 break; 104 case CPPSTATUS : 105 do_cpp_status(ifp,ofp); 106 break; 107 case CSTATUS : 108 do_c_status(ifp,ofp); 109 break; 110 case EOFSTATUS: 111 break; 112 default: 113 break; 114 } 115 } 116 } 117 int main(){ 118 FILE *ifp=fopen(INPUTFILE,"r"); 119 FILE *ofp=fopen(OUTPUTFILE,"w"); 120 if(ifp == NULL || ofp == NULL){ 121 perror(" Open failed\n"); 122 exit(1); 123 } 124 convert_work(ifp , ofp); 125 fclose(ifp); 126 fclose(ofp); 127 system("pause"); 128 return 0; 129 }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论