【问题标题】:Reading data from txt file into vectors将 txt 文件中的数据读入向量
【发布时间】:2020-03-31 18:48:22
【问题描述】:

由于其他问题,我尝试在程序的某个部分中使用 vectors 而不是数组。我以前从未真正使用过它们。

这是代码的一部分:

#include <vector>

ifstream file("data.txt");
vector<int> beds;
vector<int> people;
vector<int> balconies;

while(!file.eof()){
    file >> people.push_back();
    file >> beds.push_back();
    file >> balconies.push_back();
}

我不知道它是否会起作用。无论如何,现在我有一个错误:No matching member function for call to 'push_back'

【问题讨论】:

标签: c++ vector fstream


【解决方案1】:

std::vector::push_back 方法接受一个参数,该参数是要添加到向量末尾的值。因此,您需要将每个调用分为两个步骤:首先将值读入 int,然后将 push_back 值读入向量。

while(!file.eof()){
    int temp;
    file >> temp;
    people.push_back(temp);
    file >> temp;
    beds.push_back(temp);
    file >> temp;
    balconies.push_back(temp);
}

正如 cmets 中所述,我建议您反对您所写的while 条件。 This post 详细解释了原因,并提供了更好的替代方案。

【讨论】:

  • 您可能还想提及while (!file.eof()) 的问题。 +1。
  • @PeteBecker 好主意,添加了一个相关链接的简介。
【解决方案2】:

将输入数据存储在变量中,然后推送该变量

int example;
file >> example;
people.push_back(example);

或使用 std::istream_iterator

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-17
    • 1970-01-01
    相关资源
    最近更新 更多