Read integers from file to vector in C ++

I am trying to read an unknown number of double values ​​stored on separate lines from a text file into a vector with a name rainfall. My code will not compile; I get an error no match for 'operator>>' in 'inputFile >> rainfall'for the while while line. I understand how to read from a file to an array, but we have to use vectors for this project, and I don't get it. I appreciate any advice you can give to my incomplete 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
+4
source share
4 answers

I think you should save it in a type variable double. It seems you are doing >>to a vector, which is unacceptable. 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

@legendends2k, count. rainfall.size() .

+10

>> . :

double v;
while (inputFile >> v) {
    rainfall.push_back(v);
}

, rainfall.size() .

, ++ - istream:

// 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));
+10

:

#include <algorithm>
#include <iterator>

...
std::istream_iterator<double> input(inputFile);
std::copy(input, std::istream_iterator<double>(),    
          std::back_inserter(rainfall));
...

, STL.

+5

>> double std::vector.

std::vector - .

, , 2 :

std::ifstream inputFile{"/home/shared/data4.txt"};
std::vector<double> rainfall{std::istream_iterator<double>{inputFile}, {}};

Another solution is to define an input operator function as:

std::istream& operator>> (std::istream& in, std::vector<double>& v) {
    double d;
    while (in >> d) {
        v.push_back(d);
    }
    return in;
}

Then you can use it as in your example:

std::vector<double> rainfall;
inputFile >> rainfall;
+4
source

All Articles