繁体   English   中英

将 txt 文件中的 2d 网格读取到向量的向量中

[英]Reading a 2d grid from a txt file into a vector of vectors

我对向量没有太多经验,对于这个问题,我需要能够读取一个包含如下网格的 txt 文件:

在此处输入图像描述

我知道我想把它放入向量的向量中,所以到目前为止我已经写了这个

vector<vector<char> > map;

我在想我需要通过使用一些循环和获取行 function 来读取 txt 文件,但我不确定如何继续。

假设您有一个名为“Pet Sematary.txt”的文件,并且里面有以下引用

The soil of a man's heart is stonier, Louis.
A man grows what he can, and he tends it.
'Cause what you buy, is what you own.
And what you own... always comes home to you.

您要逐行逐字符读取并保存到 char 向量的向量中。

#include <fstream>
#include <iostream>
#include <vector>
#include <iterator>
#include <iomanip>

int main() {
    std::ifstream is("Pet Sematary.txt");
    if (!is) {
        std::cout << "Unable to open file!\n";
    }
    std::vector<std::vector<char>> grid;
    for (std::istreambuf_iterator<char> beg(is), end; beg != end; ++beg) {
        std::vector<char> tmp;
        while (beg != end && *beg != '\n') {
            tmp.emplace_back(*beg++);
        }
        grid.emplace_back(tmp);
    }
    for (auto const& line : grid) {
        for (auto const ch : line) {
            std::cout << std::setw(2) << ch;
        }
        std::cout << '\n';
    }
    return 0;
}

定义 ifstream object 并打开给定文件。 检查文件是否存在,如果它没有打印适当的消息。 定义你的网格。 使用 istreambuf_iterators 循环文件。 定义将代表您正在处理的行的向量 tmp。 虽然您正在阅读的字符不是行尾增长 tmp。 当您阅读的字符是行尾时,通过 for 的 ++beg 递增 beg 以准备 beg 下一行。 以这种方式增长网格,直到您阅读文件结尾。 当你打印网格时,你会得到这个:

 T h e   s o i l   o f   a   m a n ' s   h e a r t   i s   s t o n i e r ,   L o u i s .
 A   m a n   g r o w s   w h a t   h e   c a n ,   a n d   h e   t e n d s   i t .
 ' C a u s e   w h a t   y o u   b u y ,   i s   w h a t   y o u   o w n .
 A n d   w h a t   y o u   o w n . . .   a l w a y s   c o m e s   h o m e   t o   y o u .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM