额。。。昨天看到优快云上一堆人在讨论这个,其实一点也不难,只是看你考虑是否全面,比如:注释符号如果出现在引号中。。。
写的可能难看了一点,临时之作,见谅。。。
#include<iostream>
#include<fstream>
using namespace std;
int main(int argc,char *argv[])
{
fstream fin("in.cpp",fstream::in);
fstream fout("out.cpp",fstream::out);
char ch,prev,next=0;
bool inDoub=false;
bool inSing=false;
while(fin){
fin.get(ch);
fin.get(next);
fin.seekg(-1,fstream::cur);
switch(ch)
{
case '"':
if(prev!='/' && !inDoub)
inDoub=true;
else if(prev!='/' && inDoub)
inDoub=false;
break;
case ''':
if(prev!='/' && !inSing)
inSing=true;
else if(prev!='/' && inSing)
inSing=false;
break;
case '/':
if(inDoub || inSing)
break;
if(next=='/'){
while((ch=fin.get())!=' ');
break;
}
else if(next=='*'){
while(true){
ch=fin.get();
next=fin.get();
if(ch=='*' && next=='/'){
ch=fin.get();
break;
}
else fin.seekg(-1,fstream::cur);
if(ch==' '){
fout.put(ch);
}
}
break;
}
default:break;
}
prev=ch;
fout.put(ch);
}
fin.close();
fout.close();
return 0;
}
写的可能难看了一点,临时之作,见谅。。。
#include<iostream>
#include<fstream>
using namespace std;
int main(int argc,char *argv[])
{
fstream fin("in.cpp",fstream::in);
fstream fout("out.cpp",fstream::out);
char ch,prev,next=0;
bool inDoub=false;
bool inSing=false;
while(fin){
fin.get(ch);
fin.get(next);
fin.seekg(-1,fstream::cur);
switch(ch)
{
case '"':
if(prev!='/' && !inDoub)
inDoub=true;
else if(prev!='/' && inDoub)
inDoub=false;
break;
case ''':
if(prev!='/' && !inSing)
inSing=true;
else if(prev!='/' && inSing)
inSing=false;
break;
case '/':
if(inDoub || inSing)
break;
if(next=='/'){
while((ch=fin.get())!=' ');
break;
}
else if(next=='*'){
while(true){
ch=fin.get();
next=fin.get();
if(ch=='*' && next=='/'){
ch=fin.get();
break;
}
else fin.seekg(-1,fstream::cur);
if(ch==' '){
fout.put(ch);
}
}
break;
}
default:break;
}
prev=ch;
fout.put(ch);
}
fin.close();
fout.close();
return 0;
}
本文介绍了一个简单的C++程序,该程序能够从输入文件中移除所有类型的注释,包括单行注释(//)和块注释(/* ... */),同时考虑到了注释可能出现在字符串和字符内的特殊情况。

579

被折叠的 条评论
为什么被折叠?



