我正在尝试创建一个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;
}
第一次问问题,希望你们能明白我的意思,谢谢你的帮助
映射>>; arr[i][j];
是格式化输入。 它会跳过空格。 您必须使用不同的方法,例如std::basic_istream
下面是一个使用get()
的示例
#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;
// Skip linebreak after line: 7 7
map.ignore();
vector<vector<char> > arr(rows, vector<char>(cols));
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
// Read each char, also whitespaces and linebreaks
arr[i][j] = map.get();
}
// Skip linebreak
map.ignore();
}
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;
}
return 0;
}
我必须添加两个map.ignore();
,因为行
map >> arr[i][j];
跳过所有换行符,但
arr[i][j] = map.get();
所以我们必须手动跳过它们。
为了更好地阐明我的答案(正如Yunnosch所问)。 我的观点并不是要解决所有的问题,只是要指出为什么初始代码不能工作的问题。 真的,我没有澄清,我只是贴了一些“新”代码。
Cynthia发布的原始代码不起作用,因为operator>>
读取所有字符,直到第一个空格。 我的方法是读取整行,然后将其拆分为与初始代码相同的嵌套向量。 请注意,这也将“7 7”行作为arr
的一部分进行读取和存储
编辑:我不得不添加一些分号来编译它,我删除了“reserve”,因为它只会让新程序员感到困惑。
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
ifstream map("m.txt");
if (!map) {
cout << endl << "Failed to open file";
return 1;
}
vector<vector<char> > arr;
string line;
// no need for size at start, we can deduce it from line size
while(getline(map, line))
{
vector<char> temp;
for (auto c : line)
temp.push_back(c);
arr.push_back(temp);
}
map.close();
cout << "This is the grid from file: " << endl;
// you can always get number of rows and cols from vector size
// additionally, each line can be of different size
for (int i = 0; i < arr.size(); i++)
{
cout << "\t";
for (int j = 0; j < arr.at(i).size(); j++)
{
cout << arr.at(i).at(j);
}
cout << endl;
}
system("pause");
return 0;
}