2017-10-11 108 views
-3

我有一個.dat文件,其中包含100個整數的100個整數,我試圖將x行和x列轉換爲一個新的矢量,我設法ge第一行與所需的列,但堅持嘗試到下一行,直到x行,請給予幫助。這是我的代碼到目前爲止 也有一些幫助的顯示部分,我不知道如何顯示一個向量與多個行和列。試圖data.at(i).at(j)雙for循環,但不成功C++文件流,從.dat文件複製數據到矢量

//variable 
int row, col; 
string fname; 
ifstream file; 
vector<int> data; 

//input 
cout << "Enter the number of rows in the map: "; cin >> row; 
cout << "Enter the number of columns in the map: "; cin >> col; 
cout << "Enter the file name to write: ";   cin >> fname; 

//open file 
file.open(fname, ios::in); // map-input-100-100.dat 

int temp; 
for (int i = 0; i < col; ++i) 
{ 
    file >> temp; 
    data.push_back(temp); 
} 
// display first row of data 
for (int i = 0; i < data.size(); ++i) cout << data.at(i) << ' '; 
cout << endl; 

回答

0

的代碼可能是這樣的:

vector<vector<int>> data; // instead of your definition of data:access data[r][c] 

for (int j = 0; j < row; ++j) 
{ 
    vector<int> x(column);   
    for (int i = 0; i < col; ++i) 
    { 
     file >> temp; 
     x[i] = temp; 
    } 
    data.push_back(x); 
}