[英]Reading a text file into a 2d vector. C++
我有一个9x8的文本文件,字符之间没有空格。 如何打开文本并阅读并将其放入带有字符的2d向量中? 我到目前为止所拥有的是...
#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<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));
与第一个代码示例相同的免责声明也适用于此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.