我有一个文件映射.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@??
??_??
我将冒昧地猜测您要将文件读取到 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;
此代码将在控制台中显示您的 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;
}