///
//
// FileName : codefilter.cpp
// Creator : 温铭
// Date : 2007-3-13
// Comment : 读取一个C++文件,分离其中的注释。
// 把代码写入另外一个文件中,把注释显示在屏幕上
//
///
#include <iostream>
#include <fstream>
using namespace std;
void recomment(char ch, ifstream &infile,ofstream &outfile);
//依次读入字符,判断字符类型,进行对应操作
void in_comment( ifstream &infile); //在注释内部的相关处理
void echo_quote(char ch, ifstream &infile,ofstream &outfile); //对引号中含有注释符号的处理
void printcomment(ifstream &infile);
int main()
{
ifstream infile( "test.cpp" ); // 打开文件test.cpp用于输入
if ( !infile )
{
cerr << "cannot open test.cpp for input/n";
return -1;
}
ofstream outfile( "outfile.cpp" ); //打开文件outfile.cpp用于输出
if ( !outfile )
{
cerr << "cannot open outfile.cpp for output/n";
return -1;
}
while ( !infile.eof() )
recomment( infile.get(), infile,outfile );
infile.close();
return 0;
}
void recomment(char ch, ifstream &infile,ofstream &outfile)
{
char temp;
if (ch == '/')
{
if ( (temp = infile.get()) =='*' )
in_comment( infile ); //进入注释处理函数
else if ( temp == '/' )
printcomment( infile );
}
else if ( ch == '/'' || ch == '"' )
echo_quote(ch, infile ,outfile ); //在引号内的注释不算
else
outfile << ch;
}
void in_comment( ifstream &infile)
{
char first,second;
first = infile.get();
second = infile.get();
while ( first != '*' || second != '/' )
cout << first << second ;
}
void printcomment(ifstream &infile)
{
char ch;
while ( ( ch = infile.get() ) != '/n' )
cout << ch;
cout << endl;
}
void echo_quote(char ch, ifstream &infile,ofstream &outfile)
{
char temp;
while ( ( temp = infile.get() ) != ch )
{
cout << temp;
if ( temp == '//' ) //忽略转义字符
infile.get();
}
}