1

I'm looking for a way to read only specific sets of data from a text file. Later I need to "feed" a class with it's content and store the objects in a vector.

My problem is, that I don't need the whole content of the lines and would like to discard or ignore what's coming next and jump to the next line of the text.

I would be very happy if you have a solution or tips for me :)

Each line in the file is structured like this:

brand modelName yearOfProduction price moreStuffIDontCareAbout

Here's what I've come up with so far.

while (inputFile >> brand >> modell >> yearofproduction >> prize) {     
    vecBikes.push_back(Bike(brand, modell, yearofproduction, prize));
    getline(inputFile, puffer);
}
Buddy
  • 10,874
  • 5
  • 41
  • 58
Kai
  • 67
  • 2
  • 10

2 Answers2

-1

One can solution for this can be by putting delimiter charcter before part to be ignored. And then setting the custom delimiter character, for getline() function Code:

while (getline (inputFile,puffer,(delimiter))
{ 
 }
Vedant
  • 145
  • 1
  • 13
-1

Let's say you have a class Bike defined as such.

struct Bike {
    std::string brand, model;
    int year, price;
};

Then I suggest you define an input operator for class Bike.

std::istream& operator>>(std::istream& in, Bike& b) {
    if (std::string line; std::getline(in, line)) {
        std::istringstream line_stream{line};
        line_stream >> b.brand >> b.model >> b.year >> b.price;
    }
    return in;
}

(Note the use of the C++17 if-with-initializers syntax).

Now it is simply a matter of constructing an std::istream_iterator pair for filling your vector from any input stream (let's say the stream is called input here).

std::vector<Bike> vecBikes{std::istream_iterator<Bike>{input},
                        std::istream_iterator<Bike>{}};

Live example

Felix Glas
  • 15,065
  • 7
  • 53
  • 82