1 Replies - 11554 Views - Last Post: 10 February 2010 - 11:59 PM Rate Topic: -----

#1 thenightcrawler  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 10-February 10

C Program to Remove Comments from Another C Program

Posted 10 February 2010 - 08:57 PM

My assignment is to write a C program that strips comments from other C programs, in the style that the gcc -E preprocessor command does, and prints the resulting C program (comments removed) to STDOUT, the way the gcc -E command does.

The program does not have to handle // comments.

The program does have to handle string literals and nested comments the way the preprocessor does.

If there is an unterminated comment, the program must produce an error message with the line number where the comment begins, just as gcc -E does.

I've got it stripping the comments, and producing the error message when there's an unterminated comment.
The problem I'm having is with the handling of string literals. If there is a comment contained within a string literal, it strips the comment.

Does anyone see any glaring errors with my code?



#include <stdio.h>

#define IN (0)    /* Inside a comment */
#define OUT (1)   /* Outside a comment */

int main(void)
{
    int c;			/* current character */
    int d;                      /* next character */
    int line=0;		        /* line counter */
    int cline=0;	       /* line the current comment began on */

 int state=OUT;

  while ((c=getchar())!=EOF) {
    if (c=='\n')
      line++;
    if (state==OUT) {
      if(c != '/' && c != '"')
        putchar(c);

      if(c=='"'){
        putchar(c);
        c=getchar();
        if(c!= '"'){
          putchar(c);
	}else{
          putchar(c);
          break;
	}
      }

      if (c == '/') {
	d = getchar();
          if(d=='*'){
             cline = line+1;
	     state=IN;
	  }
      }
     }

    if(state==IN){
      if(c=='*'){
        d = getchar();
	if(d=='/'){
            state=OUT;
	}else{
	    putchar(c);
          }
      }
    }
  } /* end while */

    if((c=getchar())==EOF && state==IN){
       printf("Error: Unterminated comment at line no. %d \n", cline);
    }
 return 0;
}




Is This A Good Question/Topic? 0
  • +

Replies To: C Program to Remove Comments from Another C Program

#2 Martyn.Rae  Icon User is offline

  • The programming dinosaur
  • member icon

Reputation: 540
  • View blog
  • Posts: 1,406
  • Joined: 22-August 09

Re: C Program to Remove Comments from Another C Program

Posted 10 February 2010 - 11:59 PM

If you would like to take a look at the example code I have written in one of the C++ Tutorials entitled "Fundamentals of Parsing", you will find the solution.

Hope that helps.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1