[英]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.