-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRemoveComment.h
More file actions
51 lines (40 loc) · 1.34 KB
/
RemoveComment.h
File metadata and controls
51 lines (40 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
bluepp
2014-12-22
May the force be with me!
(F tel )
Write a program to remove the C comments(/* */) and C++
comments(//) from a file.
The file should be declared in command line.
*/
/* http://geeksquiz.com/remove-comments-given-cc-program/ */
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;
}