| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2135 人关注过本帖
标题:源代码注释过滤器
只看楼主 加入收藏
lyb661
Rank: 5Rank: 5
等 级:贵宾
威 望:18
帖 子:47
专家分:83
注 册:2018-12-12
结帖率:71.43%
收藏
 问题点数:0 回复次数:0 
源代码注释过滤器
//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编辑过]

搜索更多相关主题的帖子: Context get break case return 
2019-02-09 13:49
快速回复:源代码注释过滤器
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014694 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved