【问题标题】:Reading a text file into a 2d vector. C++将文本文件读入二维向量。 C++
【发布时间】:2015-02-01 17:29:09
【问题描述】:

我有一个 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;

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

【问题讨论】:

  • 如果您有在编译时已知的固定大小数据,请考虑改用std::array。然后你要么想要一个 characters 数组或 strings 数组。您需要在将数据添加到数组/向量的循环之前定义此
  • 给我们一个文件的例子。
  • ……………………………………X。 ……………………………………
  • 这将是文件的一个示例。每个空格表示一个换行符
  • @JoachimPileborg 我明白这一点,但我仍然无法读取文件并将其放入数组或向量中

标签: c++ vector 2d-vector


【解决方案1】:

这样的事情怎么样:

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++]);
}

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

注意: 上面的代码没有错误处理,没有检查输入是否有效,最重要的是没有检查超出范围数组。如果输入的行数超出预期,或者每行的字符数超出预期,您收到undefined behavior


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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-08
    • 2019-03-24
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    相关资源
    最近更新 更多