- 编写一个删除c语言程序中所有的注释语句.要正确处理带引号的字符串与字符常量
在c语言中,注释不允许嵌套 */
#include<stdio.h>
#define MAXSIZE 1000000 //允许存储的程序最大长度
int remove_comments(char str[]);
int practice1_23(void)
{
char str[MAXSIZE] = { 0 };
int c, i = 0;
freopen("C:\\\\Users\\wwwzh\\Desktop\\data.in", "r", stdin);
freopen("C:\\\\Users\\wwwzh\\Desktop\\data.out", "w", stdout);
while ((c = getchar()) != EOF && i < MAXSIZE)
{
str[i] = c;
i++;
}
if (i == MAXSIZE)
{
printf("error\n");
return 0;
}
remove_comments(str);
printf("%s", str);
return 0;
}
/* 把first到end之间的字符删除.例如str=abcdef,first=1,end=4,操作后str=aef */
static void function(char str[], int first, int end)
{
while (str[end] != '\0')
{
str[first] = str[end];
first++;
end++;
}
str[first] = '\0';
}
/* 删除注释 */
int remove_comments(char str[])
{
int i = 0;
while (str[i] != '\0')
{
int j = i + 1;
if (str[i] == '\"' && str[i - 1] != '\\')//字符串里的东西全部忽略
{
while (str[j] != '\"')//字符串结束位置
{
if (str[j] == '\\' && str[j + 1] == '\"')
j++;
j++;
}
i = j;
}
else if (str[i] == '/')
{
if (str[j] == '/') //单行注释处理开始
{
while (str[j] != '\n')
{
if (str[j] == '\\' && str[j + 1] == '\n')
j++;
j++;
}
function(str, i, j);
continue; //单行注释处理完毕
}
else if (str[j] == '*') //多行注释处理开始
{
j += 2;
while (!(str[j - 1] == '*' && str[j] == '/'))
{
j++;
}
function(str, i, j + 1);
continue; //多行注释处理完毕
}
}
i++;
}
return 0;
}