This is supposed to strip c- and cpp-style comments from a "program" that is read from standard input; input need not be a working program. Output should be whatever was passed to stdin minus comments.
The program recognizes comments, but it also eats tokens and doesn't recognize whitespace:
Code:
#include <iostream>
#include <string>
using namespace std;
enum Token_value {
CL, CR, CPP,
S='/', A='*', Q ='"', N='\n',
END
};
Token_value curr_tok = END;
bool cppcomment;
bool comment;
bool literal;
string buf;
Token_value get_token();
void remove() {
curr_tok = get_token();
switch(curr_tok) {
case S:
if(curr_tok == get_token() && !comment && !literal) {
curr_tok = CPP;
cppcomment = true;
comment = true;
}
if(curr_tok == A && !comment && !literal){
curr_tok = CL;
comment = true;
}
break;
case A:
get_token();
if(curr_tok == S && !comment && !literal) {
curr_tok = CR;
comment = false;
}
break;
case Q:
if(literal) literal = false;
else literal = true;
break;
case N:
if(cppcomment) {
cppcomment = false;
comment = false;
}
default:
break;
}
}
Token_value get_token() {
char ch = 0;
do {
if(!cin.get(ch)) return curr_tok = END;
} while (ch != '\n' && isspace(ch));
switch(ch) {
case '/':
return curr_tok=S;
case '*':
return curr_tok=A;
case '"':
return curr_tok=Q;
case '\n':
return curr_tok=N;
default:
if(!comment) buf.push_back(ch);
}
}
int main() {
cin.unsetf(ios::skipws);
while(cin) {
remove();
if(curr_tok==END) break;
}
cout << buf << '\n';
}
Example session
Code:
example% ./strip
int main() {
// This is a comment
"This is /*not*/ a //comment"
whitespace should be preserved here
}
output:
intmain(){Thisisnotacommentwhitespaceshouldbepreservedhere}
Other problems:
-- Selection statements have confusing conditions;
-- too many global variables for this program.
Thanks ; )