gpt4 book ai didi

c - 删除注释(/* 和//)和字符串

转载 作者:行者123 更新时间:2023-11-30 19:22:30 25 4
gpt4 key购买 nike

谁能告诉我以下代码有什么问题,该代码应该从输入中删除注释和字符串(但不是注释,这就是它识别注释的原因)?这与我之前的问题有关:Removing comments with a sliding window without nested while loops

#include <stdio.h>

int main()
{
int c, c1 = 0, c2 = 0 ,state = 0, next = 0;
while(1)
{
switch(state)
{
case 0: next = ((c2 == '*' && c1 == '/') ? 1 : (c2 == '\"') ? 2 : (c2 == '/' && c1 == '/') ? 3 : (c2 == '\'') ? 4: 0); break;
case 1: next = ((c2 == '/' && c1 == '*') ? 0 : 1); break;
case 2: next = ((c2 == '\"' && c1 != '\\') ? 0 : 2); break;
case 3: next = ((c2 == '\n') ? 0 : 3); break;
case 4: next = ((c2 == '\'' && c1 != '\\') ? 0 : 4); break;
default: next = state;
}
c = getchar(); if( c < 0) break;
c1 = c2; c2 = c; // slide window
if(state == 1)
{
if(c2 == '*')
{
c = getchar();
c1 = c2; c2 = c;
if(c2 != '/')
putchar(c1);
}
else
putchar(c2);
}
else if(state == 2)
{
if(c2 != '"' || (c2 == '\"' && c1 != '\\'))
putchar(c2);
}
else if(state == 3)
{
putchar(c2);
}
else
state = next;
// c2 is the current input byte and c1 is the previous input byte
}
return 0;
}

最佳答案

我认为您实际上不需要滑动窗口来完成删除 C 和 C++ 注释的任务。您可以扩展状态机以包含一些用于跟踪逃逸的附加状态等...状态越多,代码就会变得更大一些,但它可能在概念上使其更简单,因为您只有>一个要跟踪的状态。因此,将代码的精神转换为我建议的新状态机公式,您将得到下面的代码(我也同意 Basile 使用枚举的建议并将其包含在内)。

#include <stdio.h>

int main()
{
enum {
START, SLASH,
STRING, CHAR, STRING_ESCAPE, CHAR_ESCAPE,
SINGLE_LINE_COMMENT, MULTI_LINE_COMMENT, MULTI_LINE_END,
} state = START;
int c;

while ((c = getchar()) != EOF) {
switch (state) {
case START:
state_START:
if (c == '/') { state = SLASH; break; }
putchar(c);
if (c == '\"') state = STRING;
else if (c == '\'') state = CHAR;
break;
case SLASH:
if (c == '/') state = SINGLE_LINE_COMMENT;
else if (c == '*') state = MULTI_LINE_COMMENT;
else { state = START; goto state_START; }
break;
case STRING:
putchar(c);
if (c == '"') state = START;
else if (c == '\\') state = STRING_ESCAPE;
break;
case CHAR:
putchar(c);
if (c == '\'') state = START;
else if (c == '\\') state = CHAR_ESCAPE;
break;
case SINGLE_LINE_COMMENT:
if (c == '\n') state = START;
break;
case MULTI_LINE_COMMENT:
state_MULTI_LINE_COMMENT:
if (c == '*') state = MULTI_LINE_END;
break;
case STRING_ESCAPE:
putchar(c);
state = STRING;
break;
case CHAR_ESCAPE:
putchar(c);
state = CHAR;
break;
case MULTI_LINE_END:
if (c == '/') state = START;
else { state = MULTI_LINE_COMMENT; goto state_MULTI_LINE_COMMENT; }
break;
}
}
return 0;
}

关于c - 删除注释(/* 和//)和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16105194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com