c - Removing comments with a sliding window without nested while loops -


i'm trying remove comments , strings c file c code. i'll stick comments examples. have sliding window have character n , n-1 @ given moment. i'm trying figure out algorithm not use nested whiles if possible, need 1 while getchar through input. first thought while through find when n=* , (n-1)=/ while through until n=/ , (n-1)=*, considering has nested whiles feel inefficient. can way if have to, wondering if had better solution.

the algorithm written 1 while loop this:

while ((c = getchar()) != eof) {     ... // looking @ byte read      if (...) // symbol not inside comment     {         putchar(c);     } } 

to decide whether input char belongs comment, can use state machine. in following example, has 4 states; there rules traversing next state.

int state = 0; int next_state; while ((c = getchar()) != eof) {     switch (state)     {         case 0: next_state = (c == '/' ? 1 : 0); break;         case 1: next_state = (c == '*' ? 2 : c == '/' ? 1 : 0); break;         case 2: next_state = (c == '*' ? 3 : 2); break;         case 3: next_state = (c == '/' ? 0 : c == '*' ? 3 : 2); break;         default: next_state = state; // never happen     }      if (state == 1 && next_state == 0)     {         putchar('/'); // correct output when slash not followed star     }     if (state == 0 && next_state == 0)     {         putchar(c);     }     state = next_state; } 

the example above simple: doesn't work correctly /* in non-comment contexts in c strings; doesn't support // comments, etc.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -