[英]how read char array(with some space) from file in c++
我正在尝试在 txt 文件中创建一个迷宫 map
这是.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
这是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
的一部分
编辑:我必须添加几个分号才能编译,并且我删除了“保留”,因为它只会让新程序员感到困惑。
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.