【发布时间】:2020-10-26 16:24:13
【问题描述】:
我正在尝试在 txt 文件中创建迷宫地图
这是 .txt 文件
7 7
e%
%% %%
%% %%%
%%% %%%
% %
% %
x % %%
7 和 7 分别是行数和列数。空格也是数组的内容/ 如何在 C++ 中打印空格
我已尝试为它编写代码,但它不适用于空格:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
ifstream map("m.txt");
if (!map) {
cout << endl << "Failed to open file";
return 1;
}
int rows = 0, cols = 0;
map >> rows >> cols;
vector<vector<char> > arr(rows, vector<char>(cols));
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
map >> arr[i][j];
}
}
map.close();
cout << "This is the grid from file: " << endl;
for (int i = 0; i < rows; i++)
{
cout << "\t";
for (int j = 0; j < cols; j++)
{
cout << arr[i][j];
}
cout << endl;
}
system("pause");
return 0;
}
第一次提问希望各位大神指点一下,谢谢大家的帮助
【问题讨论】:
-
“它不起作用” 是什么意思?请描述问题。
map >> arr[i][j];是格式化的输入。它跳过空格。您必须使用不同的方法,例如std::basic_istream<CharT,Traits>::get 或 std::basic_istream<CharT,Traits>::getline -
非常感谢,我会阅读并再试一次
-
map是一个非常糟糕的变量名称。一个更好的名字是map_file。