如何将文本文件行读为向量
How to read text file lines into vectors?
我需要将输入文件中的一些行读取到vector(整数(,而C 对我来说是新的,因此我很难理解具有许多功能的巨大代码。你能告诉我如何做到这一点吗?
在我的文件中,我有类似的东西:
5 6 11 3 4
2 3 1
1
9
我用另一个程序编写了输入文件,因此我可以在其中显示向量的数量(在这种情况下为4(及其大小(5,3,1,1(,如果我使阅读更容易。
我的意思是我可以以任何形式提供信息...只需要知道哪一个更好以及如何使用它。
它不是真正的'基本方法',但它很短并且有效:
#include <fstream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::vector<std::vector<int>> vec;
std::ifstream file_in("my_file.txt");
if (!file_in) {/*error*/}
std::string line;
while (std::getline(file_in, line))
{
std::istringstream ss(line);
vec.emplace_back(std::istream_iterator<int>(ss), std::istream_iterator<int>());
}
}
稍作简化的版本,可以做同样的事情:
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::vector<std::vector<int>> vec;
std::ifstream file_in("my_file.txt");
if (!file_in) {/*error*/}
std::string line;
while (std::getline(file_in, line)) // Read next line to `line`, stop if no more lines.
{
// Construct so called 'string stream' from `line`, see while loop below for usage.
std::istringstream ss(line);
vec.push_back({}); // Add one more empty vector (of vectors) to `vec`.
int x;
while (ss >> x) // Read next int from `ss` to `x`, stop if no more ints.
vec.back().push_back(x); // Add it to the last sub-vector of `vec`.
}
}
我不会称弦乐为基本功能,但是如果没有它们,请做您想做的事情会更加混乱。
这是一个简单的示例,其中std::istringstream
用于提取每行的值。
(请注意,在阅读之前不必致电Eof((。(
std::ifstream file("file.txt");
std::vector<std::vector<int>> vectors;
std::string line;
while (std::getline(file, line))
{
std::istringstream ss(line);
std::vector<int> new_vec;
int v;
while (ss >> v) // populate the new vector
{
new_vec.push_back(v);
}
vectors.push_back(new_vec); // append it to the list of vectors
}
file.close();
相关文章:
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 如何在目录及其子文件夹中构建文件名字符串向量?
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 从.txt文件读取到C++中的双精度向量
- 遍历对象向量,并找到与从文本文件中提取的对象匹配的变量
- C++ 将 CSV 文件的列写入向量
- 数组向量的文件 I/O
- 如何在C++中将.csv文件的元素存储到二维向量中?
- 包含换行符分隔的单词的文件和C++中这些单词的字符串向量的大小是否相同?
- C++文件中的向量
- 如何从输入文件中读取字符并将其存储到向量中?
- 如何从文件中为C++中的向量赋值?
- 将无符号字符的向量写入二进制文件 c++
- 通过将文本文件读取为字符串/向量来计算加权/未加权 GPA
- 如何将目录中的文件属性填充到结构向量中?
- 如何从文件中读取 n 个字节并使用<uint8_t>迭代器将它们放入向量中?
- 类对象的向量C++文件返回程序