【发布时间】:2015-07-01 17:40:48
【问题描述】:
我在 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
}
}
移除 cmets 功能
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();
}
谢谢!
【问题讨论】:
-
a) 在 C++ 中删除 cmets 的程序不可能那么容易 => 你做错了。字符串文字、预处理器命令等。 ...?
-
这是基本的,只是去掉了“//”和“/*”样式的cmets
-
你能告诉我们为什么它不起作用,即。具体问题?
-
@Naan 是的,我明白这一点。首先没有其他类型的 cmets。
-
只使用正则表达式,整个程序大约 10 行
标签: c++ visual-studio-2012 visual-c++ fstream