0

this code removes comments

please help in correcting the code

//Program to print a file by removing Comments

#include<stdio.h>
void main()
{
    FILE *fp;
    char ch;
    //clrscr();
    fp=fopen("temp.txt","r");
    while(1)
    {
        ch=fgetc(fp);

        if(ch==EOF)
        break;
        else
        {
            if(ch=='/'){
            ch=fgetc(fp);
            if(ch=='/') 
            {
                while(1)
                {
                    ch=fgetc(fp);
                    if(ch=='\n')
                    goto label;
                }
            }
            if(ch=='*')
            { 
                while(1)
                {
                    ch=fgetc(fp);
                    if(ch=='*')
                    { 
                        ch=fgetc(fp);
                        if(ch=='/')
                        {
                            while(1)
                            {
                                ch=fgetc(fp);
                                goto label;
                            }
                        }
                        else printf("*");
                    }
                }
            }
            else printf("/");
        }
    }
    label:printf("%c",ch);
    }
    fclose(fp);
}

Edited by diafol: fixed formatting

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by Salem
0

Add a FSM to your program.

Eg.

enum state_t {
  normal,
  comment_start,
  in_comment,
  comment_end
};

Then you do say

int ch;
state_t myState = normal;
while ( (ch=fgetc(fp)) != EOF ) {
  if ( state == normal ) {
    if ( ch == '/' ) {
      // could be the start of a comment, advance state
      state = comment_start;
    } else {
      // any other char, just print it
    }
  } else
  if ( state == comment_start ) {
    if ( ch == '*' ) {
      // really is the start of a comment
      state = in_comment;
    } else {
      // the / was not part of "/*", so print it and revert back to normal
      state = normal;
    }
  } else
  if ( state == comment_end ) {
  }
}

Once you've got the idea of wandering round a FSM diagram (you examine the current state and the next character, then decide what to do about it).

A key test for you will be to do the right thing for this code

int main ( ) {
  printf( "/* this is a comment */\n" );
  return 0;
}

Can you think what extra states you would need to handle this case?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.