CoconutDug CoconutDug - 3 months ago 11
C++ Question

Fill in a vector of objects using data read from a file

I am trying to read data from a file and use it to fill in a vector.

It is a

vector
of
Score
objects.

The
Score
class only has two variables, an
int
variable and a
char*
variable.

These are the only two pieces of data in the file for each Score object.

In the file, there is a score (
int
) and a time (
char*
), then a new line.

These are what I am trying to read from the file to fill the
vector
of
Score
with.

I have seen a few examples such as:

std::ifstream ifs( "data.txt" );
std::copy( std::istream_iterator<double>(ifs), std::istream_iterator<double>(),
std::back_inserter( values ) );


However I was not able to replicate it using an object instead of a variable.

How would I go about doing that? It does not necessarily have to be using
istream_iterator
.

Thank you in advance for any help!

Answer

Given a Score class of;

struct Score {
  int score;
  std::string time;
};

You will need an extraction operator (operator >>) for the stream and this type (Score), then the technique you are using should work (it will require a changing of the types);

std::ifstream& operator>>(std::ifstream& fs, Score& s)
{
  // construct sentry as required
  fs >> s.score;
  fs >> s.time;
  return fs;
}

Note; Given the relative lack of detail for the data format in the OP, I've omitted error checking on the time etc., and left out the sentry object to focus on the ability of the code use the stream extraction operator.