2012-10-15 89 views
2

我有由數千個浮點值的數據文件,我想將它們讀入一個二維矢量陣列和載體傳遞到另一個例程一旦它從存儲的彩車文件。當我運行這個代碼時,它會打印出來;閱讀文本文件導入++二維矢量用C

[0] [0] = 0,[0] [1] = 0,等等

數據文件中包含的值喜歡;

0.000579,27.560021等

int rows = 1000; 
int cols = 2; 
vector<vector<float>> dataVec(rows,vector<float>(cols)); 
ifstream in; 
in.open("Data.txt"); 

for(int i = 0; i < rows; i++){ 
    for(int j = 0; j < 2; j++){ 
     in >> dataVec[i][j];  
     cout << "[ " << i << "][ " << j << "] = " << dataVec[i][j] << endl; 
    } 
} 
in.close(); 
+2

是否文件實際上包含逗號像你這樣的表現,抑或是純粹的空白分割?如果它包含逗號,那麼你也需要提取這些逗號。 – ildjarn

+0

這樣做的原因可能是該值是cout'的'默認精度太小。添加包括的'',並改變輸出線如下:'COUT << 「[」 <<我<< 「] [」 <<Ĵ<< 「] =」 << setprecision(10)<< dataVec [i] [j] << ENDL;' – dasblinkenlight

+0

在數據文件中沒有逗號,只是由空格隔開。 setprecision沒有工作,但這是一個好主意。 – bunduru

回答

6

它看起來對我來說,該文件無法打開。你沒有測試成功,所以無論如何它都會繼續。所有的值都初始化爲零,並保持這種狀態,因爲每次讀取都失敗。我承認這是猜測,但我會把錢投入其中。 =)

+0

是的,你說得對。雖然,我不知道爲什麼它不開放。 – bunduru

+0

高度可能的imo。特別是當你認爲你獲得了「Data.txt」的相對路徑並且假定打開的文件函數總是這樣工作。通常在調試模式下,對於大多數IDE,未初始化的值通常會初始化爲0。 – ksming

+0

@OP:放入Data.txt的完整路徑而不是相對路徑,看看它是否有效。例如。 「C:/Users/User/Documents/Data.txt」例如 – ksming

-1
#include <vector> 
#include <fstream> 
#include <iostream> 

using namespace std; 

void write(int m, int n) 
{ 
    ofstream ofs("data.txt"); 
    if (!ofs) { 
     cerr << "write error" << endl; 
     return; 
    } 

    for (int i = 0; i < m; i++) 
     for (int j = 0; j < n; j++) 
      ofs << i+j << " "; 
} 

void read(int m, int n) 
{ 
    ifstream ifs("data.txt"); 
    if (!ifs) { 
     cerr << "read error" << endl; 
     return; 
    } 

    vector<float> v; 
    float a; 
    while (ifs >> a) v.push_back(a); 

    for (int i = 0; i < m; i++) 
     for (int j = 0; j < n; j++) 
      cout << "[" << i << "][" << j << "] = " 
       << v[i*n+j] << ", "; 
} 

int main() 
{ 
    write(2,2); 
    read(2,2); 

    return 0; 
} 
1

嘗試這種解決方案,它根據自己的規格工程:

#include <fstream> 
#include <iostream> 
#include <sstream> 
#include <string> 
#include <vector> 
using namespace std; 

int main(void) 
{ 

    ifstream infile; 
    char cNum[10] ; 
    int rows = 1; 
    int cols = 2; 
    vector<vector<float > > dataVec(rows,vector<float>(cols)); 

    infile.open ("test2.txt", ifstream::in); 
    if (infile.is_open()) 
    { 
      while (infile.good()) 
      { 

       for(int i = 0; i < rows; i++) 
       { 
        for(int j = 0; j < 2; j++) 
        { 

         infile.getline(cNum, 256, ','); 

         dataVec[i][j]= atof(cNum) ; 

         cout <<dataVec[i][j]<<" , "; 

        } 
       } 



      } 
      infile.close(); 
    } 
    else 
    { 
      cout << "Error opening file"; 
    } 

    cout<<" \nPress any key to continue\n"; 
    cin.ignore(); 
    cin.get(); 


    return 0; 
}