【问题标题】:Can you give me examples of odd single line comments in C++?你能给我一些 C++ 中奇怪的单行注释的例子吗?
【发布时间】:2010-12-09 18:12:25
【问题描述】:

我写了一个从 C++ 源文件中删除单行 cmets 的方法:


def stripRegularComments(text) {
  def builder = new StringBuilder()
  text.eachLine {
   def singleCommentPos = it.indexOf("//")
   def process = true
   if(singleCommentPos > -1)
   {
    def counter = 0
    it.eachWithIndex 
    { obj,i ->
     if((obj == '\'') || (obj == '"'))
      counter++
     if(i == singleCommentPos)
     {
      process = ((counter % 2) == 1)
      if(!process)
       return
     } 
    }

if(!process)
{
 def line = it.substring(0,singleCommentPos)
 builder << line << "\n"
}
else
{
 builder << it << "\n" 
}

} else { builder << it << "\n" } } return builder.toString() }

我测试了它:

println a.stripRegularComments("""
this is a test inside double quotes "//inside double quotes"
this is a test inside single quotes '//inside single quotes'
two// a comment?//other
single //comment
""")

它产生这个输出:

这是双引号内的测试“//双引号内” 这是单引号内的测试'//单引号内' 二 单身的

是否有一些我遗漏的案例?

【问题讨论】:

  • 这些是 C++ cmets。 C 使用/**/ 来分隔注释部分。
  • 我已经编辑了这个问题。谢谢!
  • 只是小费;你可能想看看正则表达式
  • 当您查看正则表达式时,请查看 Perl。在创建文本操作脚本时,Perl 非常强大且简单。
  • 我只是想知道您为什么要从源代码中删除 cmets。这似乎不是一个好主意。我的意思是我认为我们都同意源中的 cmets 是一件好事,应该受到鼓励。

标签: c++ groovy comments header


【解决方案1】:

有趣的部分由trigraphs 和续行组成。我个人最喜欢的是:

/??/
* this is a comment *??/
/

【讨论】:

  • 我还没有在源文件中看到。
  • @aviraldg:我希望没有人会做这样的事情,但它在标准范围内,所以是合法的。
  • @Geo:哎呀......是的......这是一个多行,因为它依赖于行继续(反斜杠)。我之前在评论末尾使用??/ 发现了意外的行延续 - 基本上,// a comment??/ 将注释掉以下行。技术上是多行注释,但完全是偶然的。
  • 您在第一个 * 之前有一个空格字符,这会破坏整个过程 :) 应该删除该空格字符才能使您的评论按预期工作
  • @Andrey: 哦...我真希望 MarkDown 不需要额外的代码缩进级别。这样做太容易了。谢谢。
【解决方案2】:

这总是最喜欢的:

// Why doesn't this run?????????????????????/
foo(bar);

【讨论】:

    【解决方案3】:

    处理行尾的\ 字符是在比替换cmets(阶段3)更早的翻译阶段(阶段2)执行的。因此,// 注释实际上可以在原始源文件中占据多行

    // This \
    whole thing \
    is actually \
    a single comment
    

    附:哦...我看到这已经发布了。好的,我会保持它活着只是为了提到翻译阶段:)

    【讨论】:

      【解决方案4】:
      // Single line comments can\
      actually be multi line.
      

      【讨论】:

      • 我喜欢这个语法高亮显示失败的原因。
      • @Kawa:这是 Stack Overflow 采用的有缺陷的语法高亮方法的局限性。 :-( 即使是更传统的代码,结果也是不稳定的。
      【解决方案5】:

      我认为你无法处理

        puts("Test \
          // not a comment");
      

      而这也有可能出问题:

        puts("'"); // this is a comment
      

      【讨论】:

        【解决方案6】:

        您似乎没有处理转义引号,例如:

        "Comment\"//also inside string"
        

        对比

        "Comment"//not inside string"
        

        【讨论】:

          【解决方案7】:

          我认为您错过了/* comment */ 案例。

          【讨论】:

          • 我知道,在确定我已经涵盖了 // 的案例之后,我打算这样做
          猜你喜欢
          • 1970-01-01
          • 2011-08-22
          • 1970-01-01
          • 2010-12-19
          • 2015-02-11
          • 1970-01-01
          • 2012-12-29
          • 2012-03-23
          • 1970-01-01
          相关资源
          最近更新 更多