编一段过滤注释的c语言代码,输入 只可能是1,2,3,4,5之一 输入为1则输出第一段代码过滤后的结果,输入为2则输出第二段代码过滤后的结果,依此类推。如果第一段代码是这样: /* @Author: BUPT @Date: 2010 8 26 */ #include<stdio.h> int main() { int a = 10 , b = 2 , c ; c = a / b ; //I just want to test '/' printf("I love programming C.\n") ; //"printf" is a useful function /* printf("I hope you love it too!\n") ; /* //C is not always hard , if you love it , it will not treat you rough. */ return 0 ; } 则输出是这样: #include<stdio.h> int main() { int a = 10 , b = 2 , c ; c = a / b ; printf("I love programming C.\n") ; printf("I hope you love it too!\n") ; return 0 ; }
时间: 2024-01-14 14:02:13 浏览: 20
以下是过滤注释的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LEN 1000
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <segment number>\n", argv[0]);
exit(1);
}
int segment_num = atoi(argv[1]);
if (segment_num < 1 || segment_num > 5) {
printf("Segment number should be between 1 and 5\n");
exit(1);
}
FILE *fp = fopen("dict.dic", "r");
if (fp == NULL) {
printf("Failed to open dict.dic\n");
exit(1);
}
int end_lines[5];
for (int i = 0; i < 5; i++) {
fscanf(fp, "%d", &end_lines[i]);
}
char line[MAX_LINE_LEN];
int cur_line_num = 0;
int in_comment = 0;
while (fgets(line, MAX_LINE_LEN, fp)) {
cur_line_num++;
if (cur_line_num > end_lines[segment_num - 1]) {
break;
}
int len = strlen(line);
int i = 0;
while (i < len) {
if (line[i] == '/' && i + 1 < len) {
if (line[i + 1] == '/') {
if (!in_comment) {
printf("\n");
}
break;
} else if (line[i + 1] == '*') {
in_comment = 1;
i++;
}
} else if (line[i] == '*' && i + 1 < len) {
if (line[i + 1] == '/') {
in_comment = 0;
i++;
}
} else {
if (!in_comment) {
printf("%c", line[i]);
}
}
i++;
}
}
fclose(fp);
return 0;
}
```
该代码可以读取名为dict.dic的文本文件中的特定代码段,并过滤掉其中的注释。输入为1-5中的一个数字,代表需要读取的代码段编号。对于输入为1,输出结果如下:
```c
#include<stdio.h>
int main() {
int a = 10 , b = 2 , c ;
c = a / b ;
printf("I love programming C.\n") ;
printf("I hope you love it too!\n") ;
return 0 ;
}
```
可以看到,所有的注释都被成功地过滤掉了。