【发布时间】:2014-04-22 08:53:17
【问题描述】:
我正在尝试做一个从以前编写的程序中删除 cmets 的项目。从理论上我认为它应该可以工作,但由于某种原因,输出文件最后总是为空......请以任何方式提供帮助......(PS抱歉,如果缩进马虎,复制和粘贴对我来说似乎从来没有好过)
#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;
}
}
}
【问题讨论】:
-
因为 cmets 真的很烦人,只是把代码弄得模糊不清?
-
首先,不要做
while (!someFile.eof()),它不会像你期望的那样工作。相反,例如while (std::getline(...))。原因是eofbit标志直到在您尝试从文件末尾之外读取时才设置。这意味着第一个循环将迭代一次到多次。 -
您可能还想考虑一下缩进,您显示的代码中的缩进很难理解。请记住,您可以随时编辑您的问题以在之后解决这些问题。提示:问题很可能是因为 SO 上的编辑器不能很好地处理选项卡。
-
是什么意思; line.find(/*)
-
在
main函数的第一个do ... while循环中还有一个非常大的逻辑错误。请记住,该文件尚未打开。