编写一个删除C语言程序中所有注释语句,正确处理带引号的字符串与字符常量

来源:互联网 发布:python语言的特点 编辑:程序博客网 时间:2024/05/23 13:43

//这是书上的例题,//后面的内容不能删除  字符串内的/**/能原样打印

#include<stdio.h>


void rcomment(int c);
void in_comment(void);
void echo_quote(int c);

main()
{
    int c, d;
    while((c = getchar()) != EOF)
        rcomment(c);
    return 0;
}

void rcomment(int c)
{
    int d;
    if(c == '/')
        if((d = getchar()) == '*')  //遇到*
            in_comment();
        else if(d == '/'){
            putchar(c);
            rcomment(d);
        }else{
            putchar(c);
            putchar(d);
        }
    else if(c == '\'' || c == '"') //出现单引号或者双引号
        echo_quote(c);
    else
        putchar(c);
}

void in_comment(void)     //   /*  */直接的字符略过  不打印
{
    int c, d;
    c = getchar();
    d = getchar();
    while(c != '*' || d != '/'){
        c = d;
        d = getchar();
    }
}

void echo_quote(int c)          //引号之间的字符原样输出
{
    int d;
    putchar(c);
    while((d = getchar()) != c){
        putchar(d);
        if(d == '\\')               
            putchar(getchar());  //这句话是为了让\后出现的引号不至于跳出上面的while循环 而照原样打印出来
    }
    putchar(d);
}
0 0
原创粉丝点击