用c ++打印文件中的2D数组

时间:2014-04-08 03:50:33

标签: c++ arrays file

我有一个文件Map.txt,并且在该文件中保存了一个2D数组,但每当我尝试在我的主程序中打印我的2D数组时,我就会得到疯狂的数字。代码:

  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);

保存在文件中的地图:

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

程序运行时的输出:

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

        ?
 ?a??p`Ė??p]?
??_???`Ė?
??a??#E@??
??_??

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;
}