I am using MS VS 2017 on Windows 10 Pro 64-bit. I am trying to accomplish this with c++11 standard features. I am asking in this forum because I have searched expensively and I cannot find and example which reads the data into an object with a member vector.
Below is some typical C++ code to read a text file of doubles in to a vector. This code works, as expected. The text file is passed at the command-line.
There is one double value per line in the file, as in:
1.111111
2.222222
3.333333
4.444444
5.555555
I would like to create a ClassA (for example) that has a method for reading the data in the file and populating the vector with double values.
class ClassA
{
public:
void addData( double ); // maybe even const double
//
// More code...
//
private:
vector<double> dataVector;
}
Will I be able to use the ifstream and istream_iterator instances to populate the vector in an object of ClassA ?
Or, am I going to have to do something similar to this pseudo-code:
For each number(n) in numbers:
dataObject.addData( n );
I would rather do this using the ifstream and istream iterator instances.
I have learned that the typical way of passing the ifstream instance to a method is to pass by reference.
Perhaps someone has a link to an example where this is done ??
Can anyone help me formulate a method to accomplish this ?
//
// Here I would like to populate the vector held in an object
//
vector<double> nos( start, end );
//
// NOTE: The rest of this code is just for checking and not what
// I intend to do with this ClassA object.
//
cout << "Read " << nos.size() << " numbers" << endl;
struct A {
template <typename InputIterator>
void add_data(InputIterator begin, InputIterator end)
{ std::copy(begin, end, std::back_inserter(d)); }
std::vector<double> d;
};
// usually such a function is named operator<<.
std::ostream& print_me(std::ostream& str, A const& a) {
// or, use std::ostream_iterator, if you prefer.
for (autoconst& elt: a.d) str << elt << '\n';
return str;
}
int main() {
A a;
{
std::ifstream file("my-data.txt");
using it = std::istream_iterator<double>;
a.add_data(it{file}, it{});
}
if (print_me(std::cout, a)) std::cout << "\nprinting successful!\n";
}