我在写一个用于去除注释的代码时,感觉我应该没理解错,但是自己敲出来的结果不能说完全正确。看了很久没看明白自己的问题出在哪儿了,希望能帮我看看。
我的思路大体是:
1,遇到“//”时,之后的文字直接除掉
2,遇到“/”,先看后面有没有“/”与之匹配,没有再换行匹配,一对“/”和“/”之间的文字都删掉。
如果我有什么情况忘记考虑了也请帮忙指点一下,谢谢了。
但是我修改后不知道哪儿的问题“//”后的文字删不掉。
然后我需要中间可能有空行出现会保留,但是我输入时读到空行就停了。
以下是代码:
#include <iostream>
#include <iomanip>
using namespace std;
void removeComments(istream & is, ostream & os) {
//TODO
//first get the string
int state=0;//it's important 1:same line 2:different line
int pos1 =0;//the read start
int pos2=0;//the start use to output the after content
string r;
while (getline(is, r)){
//Boolean whether the string is blank
int k =r.length();
if(k==0){
os<<'\n';
return;
}//have characters
else{
for(int i=pos1;i<k;i++){
//if it has "//"
if(r[i]=='/'&&r[i+1]=='/'){
if(i<k-2){
os<< r.substr(0,i)<<endl;
continue;}
else{
os<<'\n';
}
}
//if it has "/*"
if(r[i]=='/'&&r[i+1]=='*'){
os<<r.substr(0,i);//don't change the line
//change the state
state =1;
//the position after *
pos1=i+2;
}
//if it has "*/"
if(r[i]=='*'&&r[i+1]=='/'){
//recover
state =0;
if(i<k-2){
//continue the output
pos1=i+2;
pos2=i+2;
}
}
//when we come to the final
if(i==k-1){
if(state==1){
//different line
state=2;
pos1=0;
os<<'\n';
}
else if(state==2){
pos1=0;
}
else if(state==0){
os<<r.substr(pos2)<<endl;
pos1=0;
}
}
}
}
}
}
void TestRemoveComments(){
removeComments(cin, cout);
}
int main(int argc, char* argv[]) {
TestRemoveComments();
return 0;
}