Writing a vector to a file

I have written a function that is supposed to write a vector to a specified file.
When I build the solution, I get this error:

- Semantic error. Invalid operands to binary expression.

This is the code for the function.

1
2
3
4
5
6
7
8
void file_out(vector<task>Task, string myfilename){
    //writing vector to file

    string file_out = myfilename;
    ofstream output_file(file_out);
    ostream_iterator<task> output_iterator(output_file, "\n");
    copy(Task.begin(), Task.end(), output_iterator);
};


Thank you for any help given.
Last edited on
what is the copy function?
Write a for/while loop with iterator, and ostream operator
for(it=Task.begin();it<Task.end();it++)
output_file<< (data you want to write)...
I suspect you only supplied part of the error message.

Do you have operator<< overloaded correctly?

@xkcd83: http://www.cplusplus.com/reference/algorithm/copy/
Full error reads:

invalid operand to binary expression ('ostream_type'(aka'basic_ostream<char,std::_1::char_traits<char> >') and 'const task')

and its to do with the iterator ... still don't understand what the error is.
That still doesn't look like the full error message. What binary expression? And it doesn't look like it has anything to do with the iterator, as the types are std::ostream and const task (which again, suggests operator<< to me.)
shouldn't it matter which data member/s of the task class are you trying to copy?
Thanks, it was an error to do with const task
Sorted!
Last edited on
Perhaps a working example will be more productive.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>

class task
{
};

std::ostream& operator<<(std::ostream& os, const task&)
{
    return os << "task" ;
}

void output(std::ostream& os, const std::vector<task>& t)
{
    std::ostream_iterator<task> output_iterator(os, "\n") ;
    std::copy(t.begin(), t.end(), output_iterator) ;
}

int main()
{
    std::vector<task> taskVec(5) ;
    output(std::cout, taskVec) ;
}
task
task
task
task
task
Last edited on
Topic archived. No new replies allowed.