Program Discussion :: Basics
93 / 279
Write code to remove comment lines.
Answer:
#include
using namespace std;
string removeComments(string prgm)
{
int n = prgm.length();
string res;
/* Flags to indicate that single line and multpile line comments */
/* have started or not */
bool s_cmt = false;
bool m_cmt = false;
/* Traverse the given program */
for (int i=0; i
Asked In ::
Language:
Vivek Rai
7 Jul, 2017 9:30 AM
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<dos.h>
void main()
{
FILE *a,*b;
char fname[20],ch,tch=NULL;
int flag1=0,flag=0,count=0;
clrscr();
printf("Enter the file name (.C or .TXT)
");
gets(fname);
a=fopen(fname,"r");
if(a==NULL)
{
puts("Cannot open the source file!!!");
delay(200);
exit(1);
}
b=fopen("target.c","w");
if(b==NULL)
{
puts("Cannot create target file!!!aa");
delay(10);
exit(1);
}
while(1)
{
start:
ch=fgetc(a);
if(ch==EOF)
break;
else
{
if(ch=='/'&&count==0)
{
flag1=1;
tch=ch;
count=1;
continue;
}
else if(ch=='*'&& flag1==1)
{
flag=1;
flag1=0;
tch=NULL;
}
else if(ch=='*'&&flag==1)
{
count=1;
continue;
}
else if(ch=='/'&&count==1)
{
flag=0;
continue;
}
else if(count==1&&flag==1)
count=0;
}
if(flag!=1)
{
if(tch>0)
fputc(tch,b);
tch=NULL;
count=0;
fputc(ch,b);
flag1=0,flag=0;
}
}
puts("DONE!! OP FILE IS "TARGET.C"
");
fcloseall();
getch();
}
Language:
Vignesh
7 Jul, 2017 9:30 AM
#include <iostream>
using namespace std;
string removeComments(string prgm)
{
int n = prgm.length();
string res;
/* Flags to indicate that single line and multpile line comments */
/* have started or not */
bool s_cmt = false;
bool m_cmt = false;
/* Traverse the given program */
for (int i=0; i<n; i++)
{
/* If single line comment flag is on, then check for end of it*/
if (s_cmt == true && prgm[i] == '\n')
s_cmt = false;
/* If multiple line comment is on, then check for end of it*/
else if (m_cmt == true && prgm[i] == '*' && prgm[i+1] == '/')
m_cmt = false, i++;
/* If this character is in a comment, ignore it*/
else if (s_cmt || m_cmt)
continue;
/* Check for beginning of comments and set the approproate flags*/
else if (prgm[i] == '/' && prgm[i+1] == '/')
s_cmt = true, i++;
else if (prgm[i] == '/' && prgm[i+1] == '*')
m_cmt = true, i++;
/* If current character is a non-comment character, append it to res*/
else res += prgm[i];
}
return res;
}
/* Driver program to test above functions*/
int main()
{
string prgm = " /* Test program */ \n"
" int main() \n"
" { \n"
" // variable declaration \n"
" int a, b, c; \n"
" /* This is a test \n"
" multiline \n"
" comment for \n"
" testing */ \n"
" a = b + c; \n"
" } \n";
cout << "Given Program \n";
cout << prgm << endl;
cout << " Modified Program ";
cout << removeComments(prgm);
return 0;
}