2016-09-25 46 views
0

我有一個數據網格的文件,我試圖迭代。我知道網格的尺寸,但似乎無法找到訪問每個位置值的方法。這裏是什麼,我在部分僞這麼遠的大綱:從double for循環中訪問文件內的元素?

std::ifstream file(filename); 

for (y = 0; y < height; y++) 
{ 
    string line = file[y]; // wrong 
    for (x = 0; x < width; x++) 
    { 
     int value = line[x] // wrong 
    } 
} 

什麼是實現這一目標的最佳方式是什麼?預先感謝您的幫助。

回答

0

應該看起來更像是這樣的:

for (int y = 0; y < height; y++) 
{ 
    string line; 
    getline(file,line); 

    std::istringstream line_stream(line); 

    for (int x = 0; x < width; x++) 
    { 
     int value; 
     line_stream >> value; 
    } 
} 
0

你不能這樣訪問流,它是在nature.Using串行數據流的僞代碼可能看起來像這樣(沒有嘗試進行編譯,但是這是這個想法)

#include <iostream>  // std::cout 
#include <fstream>  // std::ifstream 

int main() { 

    std::ifstream ifs ("test.txt", std::ifstream::in); 

#define LINE_SIZE 10  
    char c = ifs.get(); 

    for (int i=0;ifs.good();i++) { 
     // this element is at row :(i/LINE_SIZE) col: i%LINE_SIZE 
     int row=(int)(i/LINE_SIZE); 
     int col=(i%LINE_SIZE); 
    myFunction(row,col,c); 
    c = ifs.get(); 
    } 

    ifs.close(); 

    return 0; 
}