#include<iostream>
#include<fstream>
using namespace std;
void parse(ifstream &fin , ofstream &fout)
{
char curr, prev = '0';
bool comment = false;
bool charLiteral = false;
bool stringLiteral = false;
while (fin.get(curr)) {
if (charLiteral) {
fout << curr;
charLiteral = false;
}
prev = (prev == '\' && curr == '\') ? '0' : curr;
} else if (stringLiteral) {
fout << curr;
stringLiteral = false;
}
prev = (prev == '\' && curr == '\') ? '0' : curr;
} else if (comment) {
prev = '0';
comment = false;
prev = curr;
}
} else if (prev == '/') {
fout << 'n';
prev = '0';
while (fin.get() != 'n');
prev = '0';
comment = true;
fout << prev << curr;
prev = curr;
}
} else {
if (curr != '/') {
fout << curr;
}
charLiteral = (prev != '\' && curr == ''');
stringLiteral = (prev != '\' && curr == '"');
prev = (prev == '\' && curr == '\') ? '0' : curr;
}
}
}
{
if (argc != 3) {
cerr << "Usage:t" << argv[0] << " <input_file> <output_file>n";
return 1;
}
ifstream fin(argv[1]);
ofstream fout(argv[2]);
if (!fin) {
cerr << "Error:t"" << argv[1] << "" - no such filen";
return 1;
}
parse(fin, fout);
fin.close();
fout.close();
return 0;
} 复制代码
下面的内容段是关于C++编写的用于去除C、C++、Java等语言的注释的片段的内容,应该能对各位也有好处。
转载于:https://juejin.im/post/5c4a5d53e51d4550f3173d99