(筆試題)C++刪除檔案中的注釋

來源:互聯網
上載者:User

//本文演算法思想是對C++注釋的分類討論

// (1) a/b

// (2)   //a

// (3)   /*a*/

// (4) a*b

//由上述四種情況可以看出在源碼中第一次遇到'/'時須分(1),(2),(3)三種情況來討論,其他均直接輸出字元即可。

//一旦第一次發現'/'則繼續讀入並處理,只需再讀入一個字元即可分辨(1),(2)和(3).他們分別是

//'b'一般字元(說明剛才讀入的'/'不是注釋,應連同剛才的'/'一起輸出);

// '/'單行注釋的開始(繼續讀入直到出現換行表示單行注釋的結束);

//'*'多行注釋的開始(繼續讀入直到讀入'/'表示多行注釋的結束,因為C++中注釋不允許嵌套。)

//演算法如下

#include<iostream>
#include<fstream>
using namespace std;

void main()
{
 ifstream fin;
 fin.open("main.cpp",ios::in);
 fin.seekg(ios::beg);
 //get ch1 first and then get ch2
 char ch1,ch2;//
 //cout<<"a/b=?"<<endl;
 //Experiment.........
 while(fin.get(ch1))
 {
  if(ch1=='/')
  {
   fin.get(ch2);
   if(ch2=='/')
   {
    while(fin.get(ch1))
     if(ch1=='/n')
     {
      cout<<'/n';
      break;
     }
     /*************
     Experiment********/
    continue;
   }
   else if(ch2=='*')
   {
    while(fin.get(ch1))
     if(ch1=='/')
      break;
    continue;
   }
   else cout<<ch1<<ch2;
  }//endif
  cout<<ch1;
 }//endwhile
 fin.close();
}

缺點是留下了空行

下面給出的方法是用了Boost庫中的Regex庫regex

思路是對//...和/*...*/進行刪除

但是刪除之後源碼的格式不能正常的對齊,下面的思路考慮到了這一點。

另外,源碼本身可能包括了//...但不是注釋,如:boost::regex regstart("^(//.*?\\n\\s*)|(/\\*(.|\\n)*?\\*/\\s*)");

如何將上面的保留下來?這裡用了一個假設,所有的注釋要麼在一行的開始,要麼前面只能是空格個table

這時,刪除空格及其後面的注釋,並補充空格

或者,刪除table及其後面的注釋,並補充table,從而保持源碼的格式不變。

代碼如下(代碼中加入了各種注釋,運行結果是刪除注釋之後的源碼):

#include <iostream>#include <string>#include<fstream>#include <boost/regex.hpp>#include <boost/lexical_cast.hpp>using namespace std;//test0using namespace boost;// /*a*/int main() {//...//test1//boost::regex regstart("^(//.*?\\n\\s*)|(/\\*(.|\\n)*?\\*/\\s*)");boost::regex regblank("\\x20(//.*?\\n\\s*)+");//boost::regex regblank("(\\x20(//.*?\\n\\s*))*");boost::regex regtable("\\x09(//.*?\\n\\s*)+");std::string s;/**//////* / *//**/ifstream fin;/*/ */fin.open("main.cpp",ios::in);/*。。。/*/while (true){char c;fin.get(c);if (fin.eof()){break;}s+=lexical_cast<string>(c);}cout<<"Before delete:"<<endl<<s<<endl;/*cout<<s<<endl;*/s=regex_replace(s,regstart,"");cout<<"Delete start from blank:\n"<<s<<endl;s=regex_replace(s,regblank,"\\x20");cout<<"Delete start from table:\n"<<s<<endl;s=regex_replace(s,regtable,"\\x09");//s=regex_replace(s,reg1,"");cout<<s<<endl;fin.close();}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.