【发布时间】:2021-12-04 09:09:51
【问题描述】:
我想读取一个名为 maze.txt 的文件,其中包含 0 和 1(指示是否被阻止),并将文件中的每个元素存储到名为 maze[17][17] 的二维数组中。
maze.txt 就像:
11111111111111111
10000000000101001
10100111111001101
10101100001010101
10111010100000001
10000011011111001
11111000010001001
10110010000100101
10110100101110111
10000111000100001
10110011000100101
10110010000011101
10111001111110101
10110010000010001
10010111110101111
10010000000000001
11111111111111111
我搜索到的最接近的答案是使用getline() 加上istringstream()
(参考:Read from file in c++ till end of line?)
但上述解决方案仅适用于我在它们之间放置一个空格,例如:
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1
1 0 1 0 0 1 1 1 1 1 1 0 0 1 1 0 1
1 0 1 0 1 1 0 0 0 0 1 0 1 0 1 0 1
1 0 1 1 1 0 1 0 1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 1 1 0 1 1 1 1 1 0 0 1
1 1 1 1 1 0 0 0 0 1 0 0 0 1 0 0 1
1 0 1 1 0 0 1 0 0 0 0 1 0 0 1 0 1
1 0 1 1 0 1 0 0 1 0 1 1 1 0 1 1 1
1 0 0 0 0 1 1 1 0 0 0 1 0 0 0 0 1
1 0 1 1 0 0 1 1 0 0 0 1 0 0 1 0 1
1 0 1 1 0 0 1 0 0 0 0 0 1 1 1 0 1
1 0 1 1 1 0 0 1 1 1 1 1 1 0 1 0 1
1 0 1 1 0 0 1 0 0 0 0 0 1 0 0 0 1
1 0 0 1 0 1 1 1 1 1 0 1 0 1 1 1 1
1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
我的代码:
void read_maze(int map[17][17]) {
ifstream read_file("D:/maze.txt", ios::in);
if (read_file.good()){
string str;
int i = 0;
while (getline(read_file, str) {
int j = 0;
istringstream ss(str);
int num;
while (ss >> num)
{
map[i][j] = num;
j++;
}
i++;
}
}
for (int i = 0; i < 17; i++)
{
for (int j = 0; j < 17; j++)
{
cout << map[i][j];
}
cout << endl;
}
read_file.close();
}
输出类似于原来的 maze.txt
那么,我应该怎么做才能将maze.txt中的每个元素存储到一个数组中而不修改它的内容呢?
我相信可能有一些更简单的解决方案,但由于我是 C++ 的新手,我找不到像我这样的类似情况。
希望有人可以根据上面的代码提供详细的代码。 非常感谢!
【问题讨论】:
-
你为什么不用char c;而是在嵌套循环中调用
read_file >> c;?然后剩下的就是把 c 转换成一个整数,比如num = c - '0'; -
感谢@nurettin,您的解决方案对我来说非常有效且非常清晰!看来我几个小时的工作你在几秒钟内就解决了:)
-
其实20年前就解决了,花了好几个小时。
标签: c++ arrays matrix iostream