0

我有一个 9x8 文本文件,字符之间没有空格。如何打开此文本并阅读它并将其放入带有字符的二维向量中?到目前为止我所拥有的是这个......

#include <iostream>
#include <fstream>
std::ifstream in_str("inputtxt.txt");
std::string line;
while (std::getline(in_str,line))
{}
std::vector<std::vector<std::string>> replacements;

我仍在尝试弄清楚如何设置它并将文件添加到向量中

4

1 回答 1

0

像这样的东西怎么样:

std::array<std::array<char, 8>, 9> characters;

std::string line;
size_t pos = 0;
while (std::getline(in_str, line))
{
    std::copy(std::begin(line), std::end(line),
              std::begin(characters[pos++]);
}

这将从输入文件中读取行,并将所有字符复制到数组中。

注意:上面的代码没有错误处理,没有检查输入是否有效,最重要的是没有检查超出数组的范围。如果输入的行数多于预期,或者每行的字符数多于预期,您获得未定义的行为


另一种可能的解决方案,如果您愿意存储字符串(当然可以使用数组/向量之类的数组索引语法访问),您可以执行例如

std::array<std::string, 9> characters;
std::copy(std::istream_iterator<std::string>(in_str),
          std::istream_iterator<std::string>(),
          std::begin(characters));

与第一个代码示例相同的免责声明也适用于此处。

于 2015-02-01T20:29:13.627 回答