Can anyone tell me whats wrong with the following code that's suppose to remove comments and strings from an input (but not comments that's why it recognizes comments)? This is related to a prior question of mine: 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 == '
') ? 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;
}
See Question&Answers more detail:os