2016-09-25 1 views
0

나는 반복을 시도하는 숫자의 그리드가있는 파일을 가지고있다. 그리드의 크기를 알고 있지만 각 위치의 값에 액세스 할 수있는 방법을 찾지 못하는 것 같습니다. 지금까지 내가 부분 의사 코드에서 얻은 바를 요약하면 다음과 같습니다.이중 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; 
}