gpt4 book ai didi

c++ - 在 C++ 中从文件打印二维数组

转载 作者:行者123 更新时间:2023-11-28 06:57:51 25 4
gpt4 key购买 nike

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

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

保存在文件中的 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@??
??_??

最佳答案

我将冒险猜测您想要将文件读入二维字符数组。为简单起见,我还将假设您知道需要多少行和多少列。以下数字仅供引用。

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

关于c++ - 在 C++ 中从文件打印二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22927166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com