2014-01-28 71 views
0

我有一個三列的文本文件。我只想讀第一和第三。第二列由名稱或日期組成。如何從C++文本文件中讀取時跳過特定列?

輸入文件                                        |數據讀取

7.1 2000-01-01 3.4   | 7.1 3.4

1.2 2000-01-02 2.5 | 1.2 2.5

5.5未知3.9 | 5.5 3.9

1.1未知2.4 | 1.1 2.4

有人能給我一個提示如何在C++中做到這一點?

謝謝!

+0

LihO,謝謝你的幫助。 但是,當我有一個文件與幾列我如何閱讀他們。但總是跳第二列。 –

回答

0

有人可以給我一個提示如何在C++中做到這一點?

只需使用std::basic_istream::operator>>把跳過數據到一個虛擬變量,或使用std::basic_istream::ignore()跳過輸入,直到指定下一個字段分隔符。

解決應當讀出由線線的最佳方式使用std::ifstream(參見std::string::getline()),然後解析(並跳過列如上所述)分開的每一行,在循環中使用std::istringstream超過在輸入文件中的所有行。

1

「有人能給我一個提示如何在C++中做到這一點?」

沒問題:

  1. 經過使用std::getline行文件行,讀每一行成std::string line;
  2. 構建一個臨時std::istringstream對象每一行
  3. 使用>>運營商在此流填寫double類型的變量(第1列)
  4. 再次使用>>將第2列讀入std::string,你不會真正使用
  5. 使用>>閱讀另double(第3列)

即是這樣的:

std::ifstream file; 
... 
std::string line; 
while (std::getline(file, line)) { 
    if (line.empty()) continue;  // skips empty lines 
    std::istringstream is(line); // construct temporary istringstream 
    double col1, col3; 
    std::string col2; 
    if (is >> col1 >> col2 >> col3) { 
     std::cout << "column 1: " << col1 << " column 3: " << col3 << std::endl; 
    } 
    else { 
     std::cout << "This line didn't meet the expected format." << std::endl; 
    } 
} 
0

問題解決如下:

int main() 
{ 
ifstream file("lixo2.txt"); 
string line; int nl=0; int nc = 0; double temp=0; 

vector<vector<double> > matrix; 

while (getline(file, line)) 
{ 
size_t found = line.find("Unknown"); 
line.erase (found, 7); 
istringstream is(line); 

vector<double> myvector; 

while(is >> temp) 
{ 
    myvector.push_back(temp); 
    nc = nc+1; 
} 
matrix.push_back(myvector); 

nl =nl+1; 
} 

return 0; 
} 

謝謝大家!

相關問題