如何在 C++ 中从文件中读取字符数组(带有一些空格)

how read char array(with some space) from file in c++

本文关键字:数组 空格 字符 C++ 读取 文件      更新时间:2023-10-16

我正在尝试在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

下面是一个带有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所问的那样(。我的观点不是解决所有问题,只是指出为什么初始代码不起作用的问题。没错,我没有澄清,我只发布了一些"新"代码。

辛西娅发布的原始代码不起作用,因为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;
}