如何将外部文件中的数据保存到2D阵列? (C ++)

问题描述 投票:-1回答:1

我正在用C ++制作一个简单的控制台游戏,我希望能够从.txt文件中读取地图并将其保存为2D数组。我相信使用fstream可以做到这样的事情。 我也不确定是否可以根据地图与外部文件的大小来创建2D数组的大小。

我试图让它工作有点像这样:


.txt file in which i'm taking map from:

11111 10001 10001 10001 11111


The actual 2D array:
char map[][] = { {1,1,1,1,1},
                 {1,0,0,0,1},
                 {1,0,0,0,1},
                 {1,0,0,0,1},
                 {1,1,1,1,1} }


I'm a bit of a newbie when it comes to C++ so I don't quite understand everything yet. This is one of my first times reading from an external file so don't expect much from me :)

任何帮助表示赞赏!

c++ multidimensional-array fstream ifstream
1个回答
0
投票

首先,在项目中添加输入文件(例如input.in,input.txt)。启动新流以从该文件读取数据。逐行读取数字并将数字放在矩阵中。

#include <fstream>
using namespace std;

ifstream f(“input.in”);//declare the stream

int matrix[num_of_rows][num_of_columns];

void read(){
for(int i=0;i<num_of_rows;i++)
for(int j=0;j<num_of_columns;j++)
f>>matrix[i][j];}
© www.soinside.com 2019 - 2024. All rights reserved.