如何解析以下文件

how to parse the following file

本文关键字:文件 下文 何解析      更新时间:2023-10-16

我在将一些python代码传输到C++时遇到了一个小问题我有一个格式像的文件

============================== There are    0   element
============================== There are    62  element
1VTZ0   13  196 196 13  196 196 184 2520    2BUKA   1   1VTZ0   1   195
1VTZ1   13  196 196 13  196 196 184 2520    2BUKA   1   1VTZ1   1   195
1VTZ2   13  196 196 13  196 196 184 2350    2BUKA   1   1VTZ2   1   195
1VTZ3   13  196 196 13  196 196 184 2470    2BUKA   1   1VTZ3   1   195
1VTZ4   13  196 196 13  196 196 184 2560    2BUKA   1   1VTZ4   1   195
1VTZ5   13  196 196 13  196 196 184 2340    2BUKA   1   1VTZ5   1   195
1VTZ6   13  196 196 13  196 196 184 3320    2BUKA   1   1VTZ6   1   195
1VTZ7   13  196 196 13  196 196 184 2820    2BUKA   1   1VTZ7   1   195
1VTZe   13  196 196 13  196 196 184 2140    2BUKA   1   1VTZe   1   195

我想做的是跳过行===================== There are 0 element。在我的原始python代码中,我只需要使用if条件:

 if (not "====="  in line2) and (len(line2)>30):

我在C++中使用了类似的if条件,但仍然无法摆脱"元素"行,我的C++代码如下:

 unsigned  pos1, pos2;
 string needle1="element"
 string needle2="====="
 Infile.open(filename.c_str(), ios::in);
 while (!Infile.eof())
 {
    if(line==" ")
    {
       cout<<"end of the file" <<endl;
       break;
    }
    getline(Infile, line);
    pos1=line.find(needle1);

    if (pos1!=string::npos&& pos2!=string::npos && (line.length()> 40))
    {
        ...........
    }

谢谢!

我不知道为什么要检查行长度,因为有更好的方法可以做到这一点。

例如,您可以对字符串进行索引(因为它是一个字符数组),然后在while循环中使用continue语句。

while (!Infile.eof()){    
  if (line[0] == '=') { // this assumes that no other lines start with '='
      continue;
    }
  if(line==" "){
     cout<<"end of the file" <<endl;
     break;
  }
  // Do whatever you need to do with the non "===... XX element" lines

}

http://www.cplusplus.com/reference/string/string/operator[]/http://www.learncpp.com/cpp-tutorial/58-break-and-continue/