刪除c/c++來源程式中的注釋

來源:互聯網
上載者:User

題目:編寫一個程式,用於處理c/c++來源程式,將來源程式中的注釋部分去掉

輸入:c/c++檔案名稱

輸出:處理後的程式源檔案

程式虛擬碼如下:

c1,c2:char
tag:int
a:讀入一個字元存入c1
if tag==0   //讀入字元不是注釋
  if c1=='/'  //可能是注釋標記
    讀入一個字元存入c2
    if c2=='*'  //為/**/注釋的開頭
      tag = 2
    else if c2=='/' //為//注釋的開頭
      tag = 1
    else //不是注釋標記
      將c1, c2儲存
  else //讀入的字元為代碼
    儲存c1
else if tag==1  //讀入的是//注釋
  if c1=='/n' //為注釋結束標記
    tag=0
else   //讀入的是/**/注釋tag==2
  if c1=='*'  //可能為注釋結束標記
    讀入一個字元賦給c2
    if c2=='/' //是/**/注釋結尾
      tag=0
  else  //注釋沒有結束
    nothing
goto a

 

 

 

程式清單如下:

//對源檔案進行掃描,刪除其中的注釋<br />#include <stdio.h><br />void scan(char *filename)<br />{<br /> int tag=0;//0:讀取的字元為代碼;1:讀取的字元為//注釋;2:讀取的字元為/**/注釋<br /> char temp1, temp2;<br /> FILE *in, *out;<br /> in = fopen(filename,"r");<br /> if(in==NULL)<br /> {<br /> printf("cannot open the input file!");<br /> }<br /> out = fopen("out.c", "w");<br /> if(out==NULL)<br /> {<br /> printf("cannot open the output file!");<br /> }<br /> temp1 = fgetc(in);<br /> while(temp1!=EOF)<br /> {<br /> printf("%c", temp1);<br /> if(0==tag)<br /> {<br /> if('/'==temp1)<br /> {<br /> temp2 = fgetc(in);<br /> if('*'==temp2)<br /> {<br /> tag = 2;<br /> }<br /> else if('/'==temp2)<br /> {<br /> tag = 1;<br /> }<br />else<br />{<br /> fputc(temp1, out);<br /> fputc(temp2, out);<br />}<br /> }<br /> else<br /> {<br /> fputc(temp1, out);<br /> }<br /> }<br /> else if(1==tag)<br /> {<br /> if('/n'==temp1)<br /> {<br /> tag = 0;<br /> }<br /> }<br /> else<br /> {<br /> if('*'==temp1)<br /> {<br /> temp2 = fgetc(in);<br />if('/'==temp2)<br />{<br /> tag =0;<br />}<br /> }<br /> }<br /> temp1 = fgetc(in);<br /> }<br /> fclose(in);<br /> fclose(out);<br />}<br />int main()<br />{<br /> char name[256];<br /> printf("please input the filename:");<br /> gets(name);<br /> scan(name);<br /> return 0;<br />}<br />

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.