简体   繁体   English

解析txt文件C++时忽略commemts

[英]Ignore commemts while parsing txt file C++

I have a large text file and I am parsing using string stream.我有一个大文本文件,我正在使用字符串流进行解析。 Text file looks like this文本文件看起来像这样

#####
##bjhbv
nvf
vbhjbj
vfjbvjf
*bj
*bvjbv
.
.
.
.
+FILE
data I want to parse from here to 
.
.
.
.
-FILE 
till here
#shv again comments
.
.

How can I parse only between +FILE to -FILE?如何仅在 +FILE 到 -FILE 之间进行解析? I can parse inside off it, but i just want to ignore above and below comments.我可以在里面解析它,但我只想忽略上面和下面的评论。 Please help me how to ignore whie reading or parsing from .txt file.请帮助我如何忽略从 .txt 文件中读取或解析的内容。 Any leads will be appreciated.,任何线索将不胜感激。,

Something like this should do it:这样的事情应该这样做:

{
  ifstream f_in(input_file_name);
  ofstream f_out(output_file_name);

  string line;
  // discard up to "+FILE"
  while (getline(f_in, line) && line != "+FILE");
  // copy up to "-FILE"
  while (getline(f_in, line) && line != "-FILE") f_out << line << endl;
}

The ifstream and ofstream will close their respective files upon leaving scope, which is why I showed them within {} . ifstreamofstream将在离开范围时关闭它们各自的文件,这就是我在{}中展示它们的原因。

As you see in the comments, you can discard above +FILE.正如您在评论中看到的,您可以丢弃上面的 +FILE。 you can use flag and condition method.您可以使用标志和条件方法。 Where use,在哪里使用,


while(some_condition)
{
 //ignore comments
 if(!std::find("#")) 
 {
   continue;
 }
 bool flag=false;
 if(!std::find("+FILE")) 
 {
   flag=true;
 }
 if(!std::find("-FILE"))
 {
   flag=false;
 }
if(flag)
 {
  ..
  ..
  ..
 }
}

You can also use enum and array index method if you have different string names.如果您有不同的字符串名称,您也可以使用枚举和数组索引方法。 If you dont want to use std::find, if you are parsing through getline ,then you can replace std::find to line.at(0) .如果您不想使用 std::find,如果您通过getline进行解析,则可以将 std::find 替换为line.at(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM