I don't think you actually need a sliding window for your task of removing C and C++ comments. You can expand your state machine to include a few additions states for tracking escapes, etc... With more states the code gets a bit bigger, but it might make it conceptually simpler since you only have one state to track. So converting the spirit of your code to the new state machine formula I'd suggest, you get the code below (and I also agree with Basile's suggestion of using enums and included it).
#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 == '
') 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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…