Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read integers from a file into a vector in C++

Tags:

c++

vector

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
like image 964
user2922063 Avatar asked Oct 26 '13 03:10

user2922063


3 Answers

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.

like image 159
rcs Avatar answered Oct 17 '22 08:10

rcs


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));
like image 40
Sergey Kalinichenko Avatar answered Oct 17 '22 07:10

Sergey Kalinichenko


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.

like image 42
Charlie Avatar answered Oct 17 '22 06:10

Charlie