2009-02-23 304 views
4

该文件包含以下数据:如何跳过用C++读取文件中的一行?

#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: error: request for member 'find' in 'tableEntry', which is of non-class type 'int'

+8

+1为编译器。你不明白哪部分错误? – xtofl 2009-02-23 10:26:40

+0

xtofl:老兄,如果我可以+1的评论,笑我的屁股:) – 2009-02-24 17:28:32

回答

9

这是更喜欢你想要什么?

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

您尝试从行中提取整数,然后尝试在整数中查找“#”。这是没有道理的,编译器抱怨说没有整数的find方法。

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

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