注册 登录
编程论坛 C++教室

源代码注释过滤器

lyb661 发布于 2019-02-09 13:49, 2508 次点击
//Code Comment Filter for C/Cpp_programming
#include<iostream>
#include<string>
#include<fstream>
using namespace std;

ifstream is;
ofstream os;

enum Context{c_comment,cpp_comment,
string_literal,char_literal,file_end};

void handle_c_comment()      //处理C风格注释
{
  char ch;
  while(is.get(ch)) {
    if(ch == '*') {
   while(is.get(ch) && ch == '*');
   if(ch == '/')
     break;
    }
  }
}

void handle_cpp_comment()    //处理C++风格注释
{
  char ch;
  while(is.get(ch) && ch != '\n');   //使用空语句否则结果会有许多空行
  os << '\n';
}

void handle_literal(char delimiter) //处理双引号与单引号内的的字符串或字符等等
{
  os << delimiter;
  char ch;
  while(is.get(ch)) {
    os << ch;
    if(ch == delimiter)
      break;
    else if(ch == '\\')      //转义字符
      is.get(ch) && os << ch;
  }
}

Context handle_code()
{
  char ch;
  while(is.get(ch)) {
    switch(ch) {
    case '/':
      if(!is.get(ch)) {
        os << '/';
        return file_end;     //乱码?
      }
      else {
        if(ch == '*')
          return c_comment;
        else if(ch == '/')   
          return cpp_comment;
        else {
          os << '/';         //除号?
          is.putback(ch);
          break;
        }
      }
    case '\"':return string_literal;
    case '\'':return char_literal;
    default:os << ch;
    }
  }
  return file_end;
}

int main()
{
  cout << "Enter the inFilename and outFilename:" << endl;
  string fromFile,toFile;
  cin >> fromFile >> toFile;
  /* 在此处键入欲输入的文件名和输出的文件名
     如果与源程序不在一个文件夹则文件名前还要加上路径
  */
  is.open(fromFile.c_str());
  os.open(toFile.c_str());
  
  Context context;
  while((context = handle_code())!= file_end)
    switch(context) {
    case c_comment:
      handle_c_comment();
      break;
    case cpp_comment:
      handle_cpp_comment();
      break;
    case string_literal:
      handle_literal('\"');
      break;
    case char_literal:
      handle_literal('\'');
      break;
    }
  is.close();
  os.close();
  return 0;
}


[此贴子已经被作者于2019-2-9 13:55编辑过]

0 回复
1