我用c ++创建了一个程序,用于删除c / c ++文件的提交,并将删除注释的版本放在另一个文件中。但是经过几个小时的调试后仍然无法正常工作。求救!
“input”是一个包含c / c ++文件的文件夹位置的字符串。 “files”是一个向量,文件夹中包含所有文件名,但不包含其位置。 我使用“输入”和“文件”来获取文件名和位置。
for (unsigned int i = 0; i < files.size();i++ ){//for loop start
iteratora++;
string filename1 = input;
filename1.append("\\");
filename1.append(files[iteratora + 2]);
cout << "\n" << filename1 << ".\n";
cout << "Iterator: " << iteratora << ".\n";
programFile.clear();
ifstream afile (filename1);//(filename1);
fstream temp ("temp/temp.txt",std::ofstream::out | std::ofstream::trunc);
string line;//variable for holding the characters in one line
remove_comments(afile,temp);
if (temp.is_open())
{
while ( getline (temp,line) )
{
//cout << line << '\n';
if (line != ""){
cout << line;
programFile.push_back(line);
line = "";
}
}
temp.close();
}
temp.clear();
if (showVerbose == true){
print_vector(programFile);//used to know what is in the file
}
}
删除评论功能
void remove_comments ( ifstream& Source , fstream& Target)
{
string line;
bool flag = false;
while ( ! Source.eof() ) // This loop is to get assure that the whole input file is read.
{
getline(Source, line); // To read line by line.
if ( flag )
{ if ( line.find("*/") < line.length() )
flag = false;
line.erase(0,line.find("*/") + 2);
}
if ( line.find("/*") < line.length() ) // searching for " /* " to eliminat it and all its content.
flag = true;
if ( ! flag )
{
for (int i = 0; i < line.length(); i++ )
{
if(i<line.length())
if ( ( line.at(i) == '/' ) && ( line.at(i + 1 ) == '/' ) ) // searching for " // " to eliminate all its content.
break;
else
Target << line[i]; // To copy lines in the output file.
}
Target<<endl;
}
}
Source.close(); // to close the opened files.
Target.close();
}
谢谢!
答案 0 :(得分:1)
查找字符串的方法在不成功的搜索时返回std :: string :: npos,所以你应该写这行
if(line.find("/*") < line.length())
如下:
if(line.find("/*") != std::string::npos)
进行类似的更改并尝试。
答案 1 :(得分:0)
这是另一种解决方案。
它会打开file.txt
并将整个文件加载到string
。然后它删除了
评论并将string
中的新数据写回file.txt
。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void) {
string source;
ifstream readFile("file.txt");
getline(readFile, source, '\0');
readFile.close();
cout<<"\n---b e f o r e -----------------------------------\n\n";
cout << source;
while(source.find("/*") != string::npos) {
size_t Beg = source.find("/*");
source.erase(Beg, (source.find("*/", Beg) - Beg)+2);
}
while(source.find("//") != string::npos) {
size_t Beg = source.find("//");
source.erase(Beg, source.find("\n", Beg) - Beg);
}
ofstream writefile("file.txt");
writefile <<source;
writefile.close();
cout<<"\n\n-- a f t e r -------------------------------------------\n\n";
cout << source;
cout<<"\n---------------------------------------------\n\n";
cout<<"\n\n";
return 0;
}