我正在尝试做一个项目,从以前编写的程序中删除注释。从理论上讲,我认为它应该工作,但由于某种原因,输出文件最终总是空的……请尽你所能提供帮助……(注:对不起,如果缩进是草率的,复制和粘贴似乎从来没有很好地为我工作)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void comment_destroyer(ifstream&,ofstream&);
int main (void) {
string filestart;
string fileend;
ifstream start;
ofstream end;
do {
cout<<"Name of the file you want to remove comments from: ";
cin >> filestart;
}
while ( start.fail() );
cout << "What is the name of the file you want to call the stripped code?: ";
cin >> fileend;
start.open ( filestart.c_str() );
end.open ( fileend.c_str() );
comment_destroyer (start, end);
start.close();
end.close();
return 0;
}
//
//Start of functions
//
void comment_destroyer(ifstream& start, ofstream& end){
string line;
bool found = false;
int i=0;
while (! start.eof()){
getline(start,line);
if (line.find("/*")<line.length())
found = true;
if (!found){
for (int i=0;i<line.length();i++)
{
if(i<line.length())
if ((line.at(i)=='/') && (line.at(i+1)=='/'))
break;
else
end<<line[i];
}
end<<endl;
}
if (found)
{
if (line.find("*/")< line.length())
found == false;
}
}
}
下面的部分是错误的。使用相等运算符而不是将false赋值给found。
if (found)
{
if (line.find("*/")< line.length())
found == false;
}
}
将==
改为=
if (found)
{
if (line.find("*/")< line.length())
found = false;
}
}
我认为你的情况不对。字符串。如果没有找到搜索项,Find返回std::string::npos。根据npos,这是-1,所以表达式
if (line.find("/*")<line.length())
found = true;
总是设置found为true