2017-10-11 80 views
0

我有一個.dat文件包含完整的100個整數100,我試圖將x行和x列轉移到一個新的向量中,我已經成功地與所需的第一行列,但堅持嘗試到下一行,直到x行,請給予幫助。 也有一些幫助的顯示部分,我不知道如何顯示一個以上的行和列的向量。嘗試data.at(i).at(j)雙for循環,但不成功C++文件流和向量

//variable 
int row, col; 
string fname; 
ifstream file; 
vector<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 map-input-480-480.dat 

//copy specified data into vector 
int count = 0, temp = 0; 
string line; 
while (count < row) 
{ 
    for (int i = 0; i < col; ++i) 
    { 
     file >> temp; 
     data[count].push_back(temp); 
    } 
    ++count; 
    getline(file, line); 
    stringstream ss(line); 

} 

//output 
for (int i = 0; i < data.size(); i++) 
{ 
    for (int j = 0; j < data[i].size(); j++) cout << data[i][j] << ' '; 
    cout << endl; 
} 

這是到目前爲止我的代碼

+0

你聽說過一個嵌套的for循環的?這將顯着幫助... – Matthew

+0

關於文件讀取循環。從這個答案選項2應該幫助你:https://stackoverflow.com/a/7868998/4581301 – user4581301

回答

0

與文件在本地試過這樣:

12 34 42 53 
32 45 46 47 
31 32 33 34 

和讀數沒有改變(你不這樣做在你的代碼中有任何行解析)。工作示例如下:

//copy specified data into vector 
string line; 
int i, j, offset, int_val; 
size_t tmp; 
i = 0; 
while(file.good() && (i<row)){ 
    getline(file, line); 
    //create one line in data 
    data.push_back(vector<int>(0)); 
    offset = 0; 
    j = 0; 
    //parse one line 
    while(1){ 
    try{ 
     int_val = stoi(line.substr(offset), &tmp); 
    }catch(const exception& e){ 
     //ending loop when no more numbers available 
     ++i; 
     break; 
    } 
    //exiting loop when reqiuered limit reached 
    if(j >= col){ 
     ++i; 
     break; 
    } 
    //save to vector 
    data[i].push_back(int_val); 
    offset += tmp; 
    ++j; 
    } 
} 
file.close();  //don't forget to close the file 

打印輸出似乎是OK