//RemoveComments.cpp:Defines the entry point for the console application.//#include"stdafx.h"#include<iostream>#include<fstream>#include<string.h>using namespacestd;voidRemovecomments (Char* BUF,intn);intMainintargcChar*argv[]) {//printf ("Hello world!\n"); stringfilename ="FileWithComments.cpp"; Ifstream fin; intlength; Char*buffer; Try{Fin.open (Filename.c_str ()); }Catch(Std::exception &e) {cout<<e.what () <<Endl; } if(Fin.is_open ()) {cout<<"success!"<<Endl; FIN.SEEKG (0, Std::ios::end); Length=Fin.tellg (); FIN.SEEKG (0, Std::ios::beg); Buffer=New Char[length]; Fin.read (buffer,length); Fin.close (); Buffer[length-1]=' /'; cout<<buffer<<Endl; Removecomments (buffer,length); cout<<"---------------------------------------"<<Endl; cout<<buffer<<Endl; } return 0;}voidRemovecomments (Char* BUF,intN) { CharC; Char*p,*end;//p Traversal string, end is end point Char*sy,*dy;//sy sign Double quote, DY sign single quote Char*XG;//XG Flag Slash/ Char*XGX,*XXG;//XGX logo/*,xxg logo * /sy=dy=xg=xgx=xxg=NULL; P=buf; End= p +N; while(p<end) {C= *p; Switch(c) { Case '"'://record the position where double quotes appear { if(sy==null&&dy==NULL) {sy=p; }Else{sy=NULL; } P++; } Break; Case '\ ''://where the single quotation marks appear { if(dy==null&&sy==NULL) {dy=p; }Else{dy=NULL; } P++; } Break; Case '/': { if(sy==null&&dy==NULL) {P++; Charc_temp = *p; if(c_temp=='/') {//You are currently encountering the "//"*p=' '; * (P-1)=' '; P++; while(*p!='\ n') { *p=' '; P++; } /*// "" "" "" "" ""*/ }Else if(c_temp=='*') {//You are currently encountering "/*"*p=' '; * (P-1)=' '; P++; XGX=p; while(true) { if(*p=='*'&&* (p+1)=='/') { *p=' '; P++; *p=' '; Break; } *p=' '; P++; } }Else{ // Nothing}} P++; } Break; default: {p++; } Break; } } }
Remove comments from c/+ + code (change comments to spaces)