Mar 20, 2013 at 1:32am UTC
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 Mar 20, 2013 at 1:42am UTC
Mar 20, 2013 at 2:28am UTC
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)...
Mar 20, 2013 at 2:47pm UTC
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.
Mar 20, 2013 at 5:24pm UTC
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.)
Mar 20, 2013 at 6:25pm UTC
shouldn't it matter which data member/s of the task class are you trying to copy?
Mar 20, 2013 at 7:39pm UTC
Thanks, it was an error to do with const task
Sorted!
Last edited on Mar 20, 2013 at 7:41pm UTC
Mar 20, 2013 at 7:48pm UTC
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 Mar 20, 2013 at 7:49pm UTC