Maxim.K. Maxim.K. - 5 days ago 6
C++ Question

C++ reading from file using std

I'm trying to read from file, and I know how to do that:

#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
using namespace std;

int main()
{
std::string filename = "data.txt";
std::ifstream from(filename);
std::vector<int> values((std::istream_iterator<int>(from)), std::istream_iterator<int>());
return 0;
}


My question is how to do the same thing in functional way:

int fromfile(std::string filename, std::vector<int> &values)
{
...
return 0;
}


The native way doesn't work:

int fromfile(std::string filename, std::vector<int> &values)
{
std::ifstream from(filename);
values((std::istream_iterator<int>(from)), std::istream_iterator<int>());
return 0;

}

Answer

Your functional way doesn't work because you're trying to use a constructor on an already constructed object - so it looks like you're trying to invoke operator() on your vector, which does not exist. However, vector does have an assign member function that does the same thing, without the need for extra parens:

int fromfile(std::string filename, std::vector<int> &values)
{
    std::ifstream from(filename);
    values.assign(std::istream_iterator<int>(from), std::istream_iterator<int>());
    return 0;
}

Although the real functional way probably looks like this (C++11) - use the function to return the vector:

std::vector<int> fromfile(std::string filename)
{
    std::ifstream from(filename)
    return {std::istream_iterator<int>(from), std::istream_iterator<int>{}};
}

As is having an int return is somewhat useless if you just have return 0...

Comments