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);
}

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?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.