预处理去掉注释:/* */
时间: 2023-07-08 17:39:19 浏览: 83
可以使用正则表达式来去掉C/C++代码中的注释,具体方法如下:
```python
import re
# 定义一个正则表达式,用来匹配注释
pattern = r'/\*(.*?)\*/'
# 读取C/C++代码文件
with open('example.cpp', 'r') as f:
content = f.read()
# 使用sub函数将注释替换为空字符串
content = re.sub(pattern, '', content, flags=re.DOTALL)
# 输出去掉注释后的代码
print(content)
```
上面的代码中,我们使用re模块的sub函数来将代码中的注释替换为空字符串。其中,正则表达式`/\*(.*?)\*/`匹配C/C++中的注释,并使用`flags=re.DOTALL`参数来让`.`匹配任意字符,包括换行符。
相关问题
C语言编译原理预处理实验去掉注释:/* xxx */
C语言编译器在预处理阶段会去掉代码中的注释,我们可以手写一个简单的预处理器来实现这个功能。具体方法如下:
```c
#include <stdio.h>
int main() {
FILE *fp;
char ch, prev;
int comment = 0;
fp = fopen("example.c", "r");
if (fp == NULL) {
printf("Failed to open file\n");
return 1;
}
while ((ch = fgetc(fp)) != EOF) {
if (comment) {
if (prev == '*' && ch == '/') {
comment = 0;
}
} else {
if (prev == '/' && ch == '*') {
comment = 1;
prev = ' ';
continue;
} else {
printf("%c", prev);
}
}
prev = ch;
}
printf("%c", prev);
fclose(fp);
return 0;
}
```
上面的代码中,我们打开一个C源代码文件,然后逐个字符读取文件内容。当遇到`/*`时,我们将`comment`标志设置为1,表示当前处于注释中。当在注释中遇到`*/`时,我们将`comment`标志设置为0,表示注释结束。在注释中的字符不会被输出到终端,否则会被原样输出。
需要注意的是,这个预处理器比较简单,只能去掉C源代码中的`/* */`注释,而不能去掉其他类型的注释,比如`//`注释。
使用Devc++编写以下代码一、 实验目的 C语言编译时需要进行预处理,其中一项是去掉注释。 二、 实验要求 注释有两种,本实验去掉其中一种:/* */。
好的,请看以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 1000
int main()
{
FILE *fp_in, *fp_out;
char input_file[MAX_LEN], output_file[MAX_LEN], line[MAX_LEN], *pos;
int len, i;
printf("请输入需要去除注释的C语言程序文件名:");
scanf("%s", input_file);
printf("请输入去除注释后的输出文件名:");
scanf("%s", output_file);
fp_in = fopen(input_file, "r");
if (fp_in == NULL) {
printf("无法打开文件 %s!\n", input_file);
return 1;
}
fp_out = fopen(output_file, "w");
if (fp_out == NULL) {
printf("无法打开文件 %s!\n", output_file);
return 1;
}
while (fgets(line, MAX_LEN, fp_in) != NULL) {
pos = strstr(line, "/*");
if (pos != NULL) {
*pos = '\0'; // 将/*前面的内容单独输出
fputs(line, fp_out);
do {
fgets(line, MAX_LEN, fp_in);
pos = strstr(line, "*/");
} while (pos == NULL);
pos += 2; // 将*/后面的内容继续扫描
} else {
pos = line;
}
while ((pos = strchr(pos, '/')) != NULL) {
if (*(pos + 1) == '/') {
*pos = '\0'; // 将//前面的内容单独输出
break;
} else {
pos += 1;
}
}
len = strlen(line);
for (i = 0; i < len; i++) {
if (line[i] != '\r' && line[i] != '\n') {
fputc(line[i], fp_out);
}
}
fputc('\n', fp_out);
}
fclose(fp_in);
fclose(fp_out);
printf("注释已经成功去除!\n");
return 0;
}
```
这段代码实现了去除C语言程序中/* */类型注释的功能,具体实现方法是扫描每一行代码,找到/*,则将/*前面的内容单独输出,然后一直读取输入文件内容,直到找到*/为止,将*/后面的内容继续扫描。另外,还需要处理//类型的注释,这种注释只需要将//前面的内容单独输出即可。