This is a good occasion to learn how a finite state machine works.
Try, for instance, the following code.
It expects its input (
C
source code with only original
C
-style (
/*...*/
) style comments) form
stdin
(the console), so redirect (using
<
) the
C
source file to be processed appropriately).
#include <stdio.h>
typedef enum
{
Idle,
WaitForStar,
InComment,
WaitForSlash,
} State;
State process_idle(int );
State process_wait_for_star(int );
State process_in_comment(int );
State process_wait_for_slash(int );
int main()
{
State state = Idle;
int i;
while ( (i = fgetc(stdin)) != EOF )
{
switch (state)
{
case Idle:
state = process_idle(i);
break;
case WaitForStar:
state = process_wait_for_star(i);
break;
case InComment:
state = process_in_comment(i);
break;
case WaitForSlash:
state = process_wait_for_slash(i);
break;
}
}
return 0;
}
State process_idle(int i)
{
if ( i == '/') return WaitForStar;
return Idle;
}
State process_wait_for_star(int i)
{
if ( i == '*' ) return InComment;
if ( i == '/' ) return WaitForStar;
return Idle;
}
State process_in_comment(int i)
{
if ( i == '*') return WaitForSlash;
putchar(i);
return InComment;
}
State process_wait_for_slash(int i)
{
if (i == '/')
{
putchar('\n');
return Idle;
}
if (i == '*')
{
putchar('*');
return WaitForSlash;
}
putchar('*'); putchar(i);
return InComment;
}