如何将文本文件行读为向量

How to read text file lines into vectors?

本文关键字:向量 文件 文本      更新时间:2023-10-16

我需要将输入文件中的一些行读取到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();