/************************************************************************
Comprehesive Examination - II sem 1999-2000
Computer Programming - I
*************************************************************************/
/*
Question:
Write a complete C program that accepts a C program as input, removes all the valid comments fromm it and prints the input program devoid of all comments. Scan the input program until a @ symbol is encountered in the input.
NOTE:
The start of a valid C comment is characterized by the presence of a / character immediately followed by a * character. The end of a comment is indicated by the presence of a * and a / character immediately following it.
But if the above pattern comes within a string literal then it is not treated as a comment.
Example:
Then the output must be:
main() {
x=y; /*This is a comment*/
/* printf("Hello"); /* This is a comment
and more comments to follow*/
/* i=0;
printf("/*This is not a comment*//*");
}@
If the input to your program is:
main() {
x=y;
printf("Hello");
i=0;
printf("/*This is not a comment*//*");
}
- O -
Congratulations! You have implemented a part of the C Preprocessor!!!!
*/
#include <stdio.h>
#define COMMENT 1
main()
{
char ch,prev=0;
int flag=0,in_string=0;
while((ch=getchar())!='@')
{
if(prev=='*' && ch=='/' && !in_string)
{
flag=0;
prev=' ';
//printf("\nComment Off\n");
continue;
}
if(prev=='/' && ch=='*' && !in_string)
{
flag=COMMENT;
//printf("\nComment ON\n");
prev=' ';
continue;
}
if(ch=='\"' && prev!='\\' && flag!=COMMENT)
{
//printf("\nToogle String\n");
in_string=!in_string;
}
if(prev=='/' && flag!=COMMENT)
putchar(prev);
if(ch!='/')
if(flag!=COMMENT)
putchar(ch);
prev=ch;
}
printf("\n");
}