user12664019
user12664019

Reputation:

Reading data from txt file into vectors

I tried to use vectors instead of arrays in one of the parts of my program, because of other problems. I have never really used them previously.

This is the part of the code:

#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();
}

I have no idea if it would be working. Anyway now I have an error: No matching member function for call to 'push_back'.

Upvotes: 1

Views: 60

Answers (2)

Cory Kramer
Cory Kramer

Reputation: 117856

The method std::vector::push_back accepts an argument, which is the value to add to the end of the vector. So you need to break each of those calls into two steps: first read the value into an int, then push_back that value into the vector.

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

As mentioned in the comments, I would suggest against your while condition as written. This post explains why in detail, along with providing better alternatives.

Upvotes: 3

santo
santo

Reputation: 417

Store input data inside a variable before and then push that variable

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

or use std::istream_iterator

Upvotes: 1

Related Questions