我目前正在开发一个加载文件的程序,然后回读给用户的行数。我只是需要一些帮助来确定何时让程序计数一行。目前我有:
getline(file, line);
if(line.empty() || line.find("//") || line.find("**") || line.find("/*") || line.find("*/"))
{ skip line }
唯一的问题是如果一个行仍然有代码但有一个注释(以下任何一个例子),它就不会计算一行:
code... //comment
code... /* comment
/* comment */ code...
任何提示或帮助?
答案 0 :(得分:0)
完成所需内容的算法如下:
(注意:此代码未经测试)
std::vector<std::string> lines;
//collect all the lines in the vector
//iterate through the vector, removing all leading and trailing whitespace characters
for(auto& line : lines)
{
std::string::size_type pos = line.find_last_not_of("\n\t ");
if(pos != std::string::npos)
line.erase(pos + 1)
pos = line.find_first_not_of("\n\t ");
if(pos != std::string::npos && pos != 0)
line.erase(0, pos);
}
//remove all comment-only lines and blank lines
bool comment_block = false;
lines.erase(std::remove_if(lines.begin(), lines.end(), [&comment_block](const std::string& line){
//if it's empty, remove it
if(line.empty())
return true;
//if it starts with "//" it can't have code after it
if(line.find("//") == 0)
return true;
//if it starts with "/*", it begins a comment block
//(or if we're already in a comment block from earlier...)
if(comment_block || line.find("/*") == 0)
{
auto pos = line.find("*/");
if(pos == std::string::npos)
{
//if we can't find "*/" in this line, this is a comment block
//so this line is all comments and it continues to the next line
comment_block = true;
return true;
}
//if we did find "*/" in this line, we are no longer in a comment block
//(if we were already)
comment_block = false;
//Also, if "*/" is the last thing in this line, it's all comments
return pos == line.length() - 2;
}
return false;
}), lines.end());