如何在解析文本C++时删除注释

how to delete comments while parsing text C++

本文关键字:C++ 删除 注释 文本      更新时间:2023-10-16

我试图使用.ppm文件中的"ifstream"来解析C++中的文本,但我希望避免文件中以字符"#"开头并在行尾结束的注释。。我可以用下面的代码跟踪注释字符。。。任何人都可以帮助了解如何在字符"\n"之前忽略其余单词?

string word;            
file>>word;
if(strcmp(word, "#")){
   //TO DO...Dismiss all characters till the end of the line
}

使用std::getline()&continue如果line[0] == '#':则为while循环

std::ifstream file( "foo.txt" );
std::string line;
while( std::getline( file, line ) )
{
    if( line.empty() )
        continue;
    if( '#' == line[0] )
        continue;
    std::istringstream liness( line );
    // pull words out of liness...
}

或者,如果#可以发生在中线,你可以忽略它之后的一切:

std::ifstream file( "foo.txt" );
std::string line;
while( std::getline( file, line ) )
{
    std::istringstream liness( line.substr( 0, line.find_first_of( '#' ) ) );
    // pull words out of liness...
}

根据要剥离的注释的复杂性,您可能会考虑使用正则表达式:

删除不在引号内的哈希注释

例如,以下哪一项将被视为评论:

# Start of line comment
Stuff here # mid-line comment
Contact "Tel# 911"

你想在#之后去掉上面的三个例子吗?

或者,如果行的第一个字符是#,您是否只将其视为注释?