2009-02-23 556 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; 
    } 
    ... 
} 
相關問題