简体   繁体   English

如何在C ++中跳过读取文件中的行?

[英]How do I skip reading a line in a file in C++?

The file contains the following data: 该文件包含以下数据:

#10000000    AAA 22.145  21.676  21.588
10  TTT 22.145  21.676  21.588
1  ACC 22.145  21.676  21.588

I tried to skip lines starting with "#" using the following code: 我尝试使用以下代码跳过以“#”开头的行:

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>

using namespace std;
int main() {
     while( getline("myfile.txt", qlline)) {

           stringstream sq(qlline);
           int tableEntry;

           sq >> tableEntry;

          if (tableEntry.find("#") != tableEntry.npos) {
              continue;
          }

          int data = tableEntry;
   }
}

But for some reason it gives this error: 但由于某种原因,它给出了这个错误:

Mycode.cc:13: error: request for member 'find' in 'tableEntry', which is of non-class type 'int' Mycode.cc:13:错误:请求'tableEntry'中的成员'find',这是非类型'int'

Is this more like what you want? 这更像你想要的吗?

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <algorithm>

using namespace std;

int main() 
{
    fstream fin("myfile.txt");
    string line;
    while(getline(fin, line)) 
    {
        //the following line trims white space from the beginning of the string
        line.erase(line.begin(), find_if(line.begin(), line.end(), not1(ptr_fun<int, int>(isspace)))); 

        if(line[0] == '#') continue;

        int data;
        stringstream(line) >> data;

        cout << "Data: " << data  << endl;
    }
    return 0;
}

You try to extract an integer from the line, and then try to find a "#" in the integer. 您尝试从该行中提取整数,然后尝试在整数中找到“#”。 This doesn't make sense, and the compiler complains that there is no find method for integers. 这没有意义,编译器抱怨没有整数的find方法。

You probably should check the "#" directly on the read line at the beginning of the loop. 您可能应该在循环开始时直接在读取行上检查“#”。 Besides that you need to declare qlline and actually open the file somewhere and not just pass a string with it's name to getline . 除此之外,您需要声明qlline并实际在某处打开文件,而不只是将带有名称的字符串传递给getline Basically like this: 基本上是这样的:

ifstream myfile("myfile.txt");
string qlline;
while (getline(myfile, qlline)) {
  if (qlline.find("#") == 0) {
    continue;
  }
  ...
}

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

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