PIYUSH SHARMA CSE-B 2100320100117
Experiment No – 3(a)
Aim: Write a Program to identify single and multiline comments
Theory:
Types of comments in programs:
Single Line Comment: Comments preceded by a Double Slash (‘//’)
Multi-line Comment: Comments starting with (‘/*’) and ending with (‘*/’).
Code:
#include <bits/stdc++.h>
using namespace std;
void comment(string s){
if (s.size()>=2 && s[0] == '/' && s[1] == '/') {
cout << "Single line Comment";
return;
if (s.size()>=4 && s[s.size() - 2] == '*'
&& s[s.size() - 1] == '/' && s[0] == '/' && s[1] == '*') {
cout << "Multiline Comment";
return;
cout << "Not a Comment"; Output:
}
int main(){
string s;
cout<<"Enter the string "<<endl;
getline(cin,s);
comment(s);
return 0;
}
PIYUSH SHARMA CSE-B 2100320100117
Experiment No – 3(a)
Aim: Write a Program to remove single and multiline comments
Theory:
Given a C++ program as input, remove the comments from it. ‘source’ is a vector where the i-th line of the
source code is the source[i]. This represents the result of splitting the source code string by the newline
character \n. In C++, we can create two types of comments, i.e., Line Comments, Block Comments.
The string ‘\’ denotes the line comment, which means the string next to it on the right will be ignored by
the program.
The string ‘\* and *\’ is a multiline comment representing the string starting from ‘\* till the *\’ will be
ignored.
The first useful comment takes precedence over others: if the string // occurs in a block comment, it is
ignored. Similarly, if the string /* occurs in a line or block comment, it is also ignored. If a certain line of
code is empty after removing comments, you must not output that line − each string in the answer list will
be non-empty.
Code:
#include <iostream>
using namespace std;
string Rcomments(string s){
int n = s.length();
string ans;
bool single_c = false;
bool multi_c = false;
for (int i=0; i<n; i++){
if (single_c == true && s[i] == '\n') single_c = false;
else if (multi_c == true && s[i] == '*' && s[i+1] == '/') multi_c = false, i++;
else if (single_c || multi_c) continue;
else if (s[i] == '/' && s[i+1] == '/') single_c = true, i++;
else if (s[i] == '/' && s[i+1] == '*')multi_c = true, i++;
else ans += s[i]; }
return ans; }
int main(){
string s;
cout<<"Enter The String 1 : "<<endl;
getline(cin,s);
cout<<" Output : ";
cout<<Rcomments(s)<<endl;
PIYUSH SHARMA CSE-B 2100320100117
cout<<"Enter The String 2 : "<<endl;
getline(cin,s);
cout<<" Output : ";
cout<<Rcomments(s);
return 0;
Output: