I am trying to read an unknown number of double values stored on separate lines from a text file into a vector called rainfall
. My code won't compile; I am getting the error no match for 'operator>>' in 'inputFile >> rainfall'
for the while loop line. I understand how to read in from a file into an array, but we are required to use vectors for this project and I'm not getting it. I appreciate any tips you can give on my partial code below.
vector<double> rainfall; // a vector to hold rainfall data
// open file
ifstream inputFile("/home/shared/data4.txt");
// test file open
if (inputFile) {
int count = 0; // count number of items in the file
// read the elements in the file into a vector
while ( inputFile >> rainfall ) {
rainfall.push_back(count);
++count;
}
// close the file
I think you should store it in a variable of type double
. Seems you are doing >>
to a vector, which is not valid. Consider the following code:
// open file
ifstream inputFile("/home/shared/data4.txt");
// test file open
if (inputFile) {
double value;
// read the elements in the file into a vector
while ( inputFile >> value ) {
rainfall.push_back(value);
}
// close the file
As @legends2k points out, you don't need to use the variable count
. Use rainfall.size()
to retrieve the number of items in the vector.
You cannot use >>
operator to read in the whole vector. You need to read one item at a time, and push it into the vector:
double v;
while (inputFile >> v) {
rainfall.push_back(v);
}
You do not need to count the entries, because rainfall.size()
will give you the exact count.
Finally, the most C++ -ish way of reading a vector is with istream iterators:
// Prepare a pair of iterators to read the data from cin
std::istream_iterator<double> eos;
std::istream_iterator<double> iit(inputFile);
// No loop is necessary, because you can use copy()
std::copy(iit, eos, std::back_inserter(rainfall));
You could also do:
#include <algorithm>
#include <iterator>
...
std::istream_iterator<double> input(inputFile);
std::copy(input, std::istream_iterator<double>(),
std::back_inserter(rainfall));
...
assuming you like the STL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With