如何解析以下文件

时间:2013-07-31 17:48:32

标签: c++ string parsing line

我有一点问题是将一些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))
    {
        ...........
    }

谢谢!

1 个答案:

答案 0 :(得分:1)

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

例如,您可以索引字符串(因为它是一个字符数组),然后在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/

相关问题