2011-03-08 8 views
6

파일의 특정 데이터를 두 개의 2D 배열로 읽으려고합니다. 첫 번째 데이터 행은 각 배열의 크기를 정의하므로 첫 번째 Array를 채울 때 해당 행을 건너 뛸 필요가 있습니다. 첫 번째 줄을 건너 뛰면 첫 번째 배열은 파일의 7 번째 줄까지 파일의 데이터로 채 웁니다. 두 번째 배열은 파일의 나머지 데이터로 채워집니다. 여기 enter image description here파일에서 배열로 데이터 읽어 오기

지금까지 내 (결함) 코드입니다 : 입력 모두를위한

#include <fstream> 
#include <iostream> 

using namespace std; 

int main() 
{ 
    ifstream inFile; 
    int FC_Row, FC_Col, EconRow, EconCol, seat; 

    inFile.open("Airplane.txt"); 

    inFile >> FC_Row >> FC_Col >> EconRow >> EconCol; 

    int firstClass[FC_Row][FC_Col]; 
    int economyClass[EconRow][EconCol]; 

    // thanks junjanes 
    for (int a = 0; a < FC_Row; a++) 
     for (int b = 0; b < FC_Col; b++) 
      inFile >> firstClass[a][b] ; 

    for (int c = 0; c < EconRow; c++) 
     for (int d = 0; d < EconCol; d++) 
      inFile >> economyClass[c][d] ; 

    system("PAUSE"); 
    return EXIT_SUCCESS; 
} 

덕분에

여기 내 데이터 파일의 표지 이미지입니다.

+1

int firstClass [FC_Row] [FC_Col];는 VLA로 C++가 아니고 C99입니다. * 일부 * C++ 컴파일러가 지원하기 때문에 이식성에는 좋지 않습니다. – Erik

+0

+1은 명확하게 그림이 그려져 있습니다. MSPaint는 +1을받습니다 :-) – corsiKa

+0

+1 프로그램 샘플을 제공합니다. –

답변

3

while 루프가 파일 끝까지 반복되므로 필요하지 않습니다. 합니다 (while없이) 대신

while (inFile >> seat) // This reads until the end of the plane. 

사용 :

for (int a = 0; a < FC_Row; a++)   // Read this amount of rows. 
    for (int b = 0; b < FC_Col; b++) // Read this amount of columns. 
     inFile >> firstClass[a][b] ; // Reading the next seat here. 

경제 좌석 동일하게 적용합니다.


또한 가변 크기 배열이 지옥이므로 배열을 벡터로 변경할 수 있습니다.

vector<vector<int> > firstClass(FC_Row, vector<int>(FC_Col)) ; 
vector<vector<int> > economyClass(EconRow, vector<int>(EconCol)) ; 

벡터를 사용하려면 #include <vector>이 필요합니다. 액세스는 배열과 동일합니다.

1

seat으로 읽은 다음이 값으로 배열을 채 웁니다. 그런 다음 다시 seat을 읽고이 새 값으로 전체 배열을 채 웁니다.

이 시도 :

int CurRow = 0; 
int CurCol = 0; 
while ((inFile >> seat) && (CurRow < FC_Row)) { 
    firstClass[CurRow][CurCol] = seat; 
    ++CurCol; 
    if (CurCol == FC_Col) { 
    ++CurRow; 
    CurCol = 0; 
    } 
} 
if (CurRow != FC_Row) { 
    // Didn't finish reading, inFile >> seat must have failed. 
} 

두 번째 루프는 economyClass을 사용해야하지 firstClass

이처럼 주위 루프를 전환하는 이유는 오류에 때 루프가 종료를 단순화 오류 처리입니다. 또는 내부 루프에 infile >> seat을 사용하여 for 루프를 유지할 수 있지만 읽기가 실패하면 두 개의 루프에서 벗어나야합니다.

2

당신은 for 루프의 순서를 변경하고 파일 읽기해야합니다

for (rows = 0; rows < total_rows; ++ rows) 
{ 
    for (col = 0; columns < total_columns; ++cols) 
    { 
    input_file >> Economy_Seats[row][column]; 
    } 
} 

나는 독자에게 잘못된 입력의 EOF 및 취급에 대한 검사 떠날거야.

관련 문제