C程序设计语言(K&R 第二版):练习1-23

题目:

编写一个删除c语言程序中所有的注释语句。要正确的处理带引号的字符串与字符常量。在c语言中注释不允许嵌套

首先需要理解什么是注释嵌套,c语言中有两种注释符,一种是行注释符//,一种是块注释符/**/

其中行注释符,一次只能注释一行,//之后的全部为注释

块注释符要成对出现,注释从/*开始到*/结束。

注释嵌套是指对块注释符所说,例如下面为注释嵌套的例子:

/* /* this is the comments */ */

注释从第一个/*开始,到第一个*/结束。所以最后一个*/不在注释范围内,这种注释是不被允许的,否则会导致编译错误

自我解答:

#include <stdio.h>

#define  IN    1
#define  OUT   0
int main()
{
    int c;
    bool comInStr = OUT;        //the comment symbol // or /* in the string
    bool blockCom = OUT;        // the character is in comment block "/**/"
    bool lineCom = OUT;         // the character is in a comment line "//"
    bool isComSymbol = false;          // if it is comment symbol "//" or "/*"
    bool outComBlock = false;   //the flag for out of comment block
    
    while((c = getchar()) != EOF)
    {
        if(comInStr)
        {
           putchar(c);       //output the content in " "
           if(c == '"')
              comInStr = OUT;  //end of the content in " "
        }
        else
        {
            if(lineCom == IN)
            {
                if(c == '\n')    // will not output until to the end of the line
                {
                    putchar(c);
                    lineCom = OUT;
                    isComSymbol = false;
                }
            }
            else if(blockCom =
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值