版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Yonggie/article/details/89474190
我有朋友向我求助写一个读取文件然后删掉注释的程序,也顺便练练手。
内容是在content里面。
下面的只是读到了content然后显示,没有改动原来文件的内容。
#include<iostream>
#include<algorithm>
#include<cstdio>
#include <stack>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;
int main(){
//read all content into content string.
ifstream rfile;
string filename="1.txt";
string contents;
string line;
rfile.open(filename.c_str());
while(getline(rfile,line)){
contents.append("\n");
contents.append(line);
}
cout<<contents<<endl;
cout<<"length of this file is "<<contents.length()<<"charactors!"<<endl<<endl<<endl;
cout<<"After deleting notation:"<<endl;
//manipulate content string
int i=0;
while(i<contents.length()-1){
//delete // type notation
if(contents[i]=='/'&&contents[i+1]=='/'){
while(contents[i]!='\n'&&i<contents.length()){
contents[i]=' ';
i++;
}
}// delete /**/ type notation
else if(contents[i]=='/'&&contents[i+1]=='*'){
int startIndex=i;
i+=2;//move to the charactor after *.
while(i<contents.length()&&!(contents[i]=='*'&&contents[i+1]=='/'))
i++;
if(i==contents.length()-1){
cout<<"illegal notation format!"<<endl;
break;
}
for(int j=startIndex;j<=i+1;j++) contents[j]=' ';
}// just move forward
else i++;
}
for(int index=0;index<contents.length();index++)
cout<<contents[index];
cout<<endl;
return 0;
}