Want a way to strip comments from a

Joe English jeenglis at nunki.usc.edu
Sun Mar 19 12:48:32 AEST 1989


leo at philmds.UUCP (Leo de Wit) writes:
>In article <4896 at cbnews.ATT.COM> smk at cbnews.ATT.COM (Stephen M. Kennedy) writes:
>|In article <9900010 at bradley> brian at bradley.UUCP writes:
>|>  The following works in vi: :%s/\/\*.*\*\///g
>|
>|/* And this */ important_variable = 42 /* doesn't work either! */
>
>And how about:
>
>    puts(" A comment /* in here */");
>
>And you can give more examples showing it isn't that trivial; a challenge
>for the sed adept, perhaps ...

Does it *have* to be done in sed/awk/other text processor?
This problem is fairly difficult to solve using regexp/editor
commands, but it's a piece of cake to do in C:

#include <stdio.h>

void eatcomment(void);

main() 
{
    int ch;
    int instring = 0;

    ch = getchar();
    while (ch != EOF) {
      switch (ch) {
	case '"' :
	  instring = !instring;
	  break;
	case '/' :
	  if (!instring) 
	    if ((ch = getchar()) == '*') { eatcomment(); ch=getchar(); }
	    else putchar('/');
	  break;
	case '\\' :         /* in case this is a \" in a string, */
          putchar('\\');    /*  pass it through now and don't let */
          ch = getchar();  /*  the switch() eat it */
      }
      putchar(ch);
      ch = getchar();
    }
    exit(0);
}

void eatcomment(void)
{
    int ch;

    for (;;) {
      ch = getchar();
      while (ch == '*')
        if ((ch = getchar()) == '/') return;
      if (ch == EOF) exit(1); /* oops */
    }
}
------------

This hasn't been tested thoroughly; it's mostly 
from memory.  

Joe English

jeenglis at nunki.usc.edu



More information about the Comp.lang.c mailing list