2014-04-08 55 views
0

我有一個文件Map.txt,裏面有一個二維數組,但是每當我嘗試在我的主程序中打印我的二維數組時,我都會看到瘋狂的數字。代碼:運行程序時在C++中打印一個二維數組

******************** 
******************** 
******************** 
******************** 
******************** 
******************** 
******************** 
**********S********* 
*****************T** 
******************** 

輸出:

cout << "Would you like to load an existing game? Enter Y or N: " << endl; 
cin >> Choice; 
if (Choice == 'Y' || Choice == 'y') 
{ 
    fstream infile; 
    infile.open("Map.txt"); 
    if (!infile) 
     cout << "File open failure!" << endl; 
    infile.close(); 
} 
if (Choice == 'N' || Choice == 'n') 
    InitMap(Map); 

地圖保存在文件

Would you like to load an existing game? Enter Y or N: 
y 
88???????`Ė 
?(?a???? 
??_? 
?дa??g @ 
[email protected] 

     ? 
?a??p`Ė??p]? 
??_???`Ė? 
??a??#[email protected]?? 
??_?? 
+3

請準確顯示文件的外觀以及實際嘗試打印的代碼的相關部分。 – merlin2011

+0

你已經顯示了打開和關閉文件的代碼。從文件中讀取二維數組的代碼以及獲取的輸出類型。 – arin1405

+0

我不知道如何從文件中讀取二維數組。 – savannaalexis

回答

1

我要大膽地說,你要閱讀的文件轉換成一個猜想2D字符數組。 爲簡單起見,我還會假設您知道需要多少行和列。以下數字僅用於說明。

#define NUM_ROWS 10 
#define NUM_COLS 20  

// First initialize the memory 
char** LoadedMap = new char*[NUM_ROWS]; 
for (int i = 0; i < NUM_ROW; i++) 
    LoadedMap[i] = new char[NUM_COLS]; 

// Then read one line at a time 
string buf; 
for (int i = 0; i < NUM_ROW; i++) { 
    getline(infile, buf); 
    memcpy(LoadedMap[i], buf.c_str(), NUM_COL); 
} 

// Sometime later, you should free the memory 


for (int i = 0; i < NUM_ROW; i++) 
    delete LoadedMap[i]; 

delete LoadedMap; 
0

此代碼將在控制檯中顯示您的Map.txt文件。不要忘記提供打開文件的確切路徑。

#include <stdio.h> 

const int MAX_BUF = 100001; 
char buf[MAX_BUF]; 

int main() 
{ 
    FILE *fp = fopen("Map.txt","r"); //give the full file path here. 
    while(fgets(buf,MAX_BUF,fp)) 
    { 
     puts(buf); 
    } 
    return 0; 
}