2012-10-05 16 views
-1

我想C++ - 逐行讀取文件,並將每行w.r.t分割爲"\t"字符以填充矩陣。我的代碼會是這樣的C++ ifstream split w.r.t.一個字符

ifstream data_x; 
     double** test_data = new double*[100]; 
     for(int j = 0 ; j < ; j++) 
      test_data[j] = new double[4]; 

    data_x.open("X.txt"); 

    int i = 0; 
    if (data_x.is_open()) 
    { 
     while (!data_x.eof()) 
     { 
      char** split = data_x.split("\t") 
      for(int k = 1 ; k < 4 ; k++) 
       test_data[i][k]; 
      i++; 
     } 
    } 

    data_x.close(); 

    ifstream data_y; 
    data_y.open("Y.txt"); 

    i = 0; 
    if (data_y.is_open()) 
    { 
     while (!data_y.eof()) 
     { 
      data_y >> test_data[i][0]; 
      i++; 
     } 
    } 

    data_y.close(); 

其中語法

char** split = data_x.split("\t") 
for(int k = 1 ; k < 4 ; k++) 
     test_data[i][k]; 

是近似的。如何正確使用C++?

感謝

+0

使用std :: string,getline和字符串庫函數。 – DumbCoder

+0

首先,使用std :: string,然後使用boost字符串算法庫來分割每一行。 –

+2

每當我看到while(!data_x.eof())''我可以保證下面的代碼是錯誤的。 (它可以以這種方式正確地完成,但是有很多整潔的成語,所以知道的人在測試中不使用eof()。) –

回答

3

假設您的文件僅包含數字,這裏的標準C++成語:

#include <vector> 
#include <string> 
#include <sstream> 
#include <fstream> 

std::ifstream infile("data.txt"); 

std::vector<std::vector<double>> matrix; 

for (std::string line; std::getline(infile, line);) 
{ 
    std::istringstream iss(line); 
    std::vector<double> row; 

    for (double d; iss >> d;) 
    { 
     row.push_back(d); 
    } 

    matrix.push_back(row); 
} 

如果知道矩陣的大小,你可以添加相關reserve呼籲避免載體重新分配。您還可以添加測試,以確定某行上是否有任何無法識別的數據,但現在這應該讓您開始。

+0

我希望C++ 11中的新移動功能涵蓋正確。 –

+0

@KerrekSB這工作正常,謝謝 – octoback

0

創建矢量出由空格分開的實體其實是微不足道的:

std::vector<T> fields(
    std::istream_iterator<T>(
     d::istringstream(line) >> std::skipws), 
    std:.istream_iterator<T>())); 

如果你細胞類型T是一些東西,會考慮其他空間比'\t'作爲分隔符,你可能想改變被認爲是空間使用修改的std::ctype<char>構面。

顯然,上面的邏輯可以打包成一些更易於使用的finction。