【问题标题】:How do I skip reading a line in a file in C++?如何跳过读取 C++ 文件中的一行?
【发布时间】:2009-02-23 06:19:59
【问题描述】:

该文件包含以下数据:

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

我尝试使用以下代码跳过以“#”开头的行:

#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;
   }
}

但由于某种原因,它给出了这个错误:

Mycode.cc:13:错误:请求 'tableEntry' 中的成员 'find',其中 是非类类型'int'

【问题讨论】:

  • +1 用于编译器。您不理解错误的哪一部分?
  • xtofl:老兄,如果我可以 +1 评论,我笑死了 :)

标签: c++ file-io


【解决方案1】:

这更像你想要的吗?

#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;
}

【讨论】:

  • 我还建议在检查注释字符之前修剪行。
  • 你说得对,我已经编辑了示例以修剪字符串的开头。
【解决方案2】:

您尝试从该行中提取一个整数,然后尝试在该整数中找到一个“#”。这没有意义,编译器抱怨没有find 整数方法。

您可能应该直接在循环开头的读取行上检查“#”。 除此之外,您需要声明qlline 并实际在某处打开文件,而不仅仅是将带有其名称的字符串传递给getline。基本上是这样的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-09
    • 2018-08-20
    • 2017-10-05
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多