Saving an inventory into a file

Hi, I was trying to save an inventory into a file so I can load it afterwards. I tried using the file_name to open the file but it didn't work. I then tried to convert to const char using .c_str() but it still doesnt work. I now get the error

no instance of constructor "std::basic_ostream<_Elem, _Traits>::basic_ostream
[with _Elem=char, _Traits=std::char_traits<char>]" matches the argument list

what should I do?
1
2
3
4
5
6
void Inventory::save(const std::string & file_name) const
{
	std::ostream ofs(file_name.c_str());
	ofs << _count;
	ofs << this << std::endl;
}
It should be std::ofstream note the 'f' for file.
Thanks, I checked my code several times but I did not notice it.
I stored my inventory in a file inventory.bat and when I checked the content, I found the address 130018FAFC. I think the address will be emptied at the end of the program

I tried to replace the last sentence in the code above with
ofs << *this << std::endl;
but it gives an error saying "No operator "<<" matches these operands"

Is there a way to solve it without overwriting the operand << ?
ofs << *this << std::endl; is at least a reasonable syntax. But it assumes your class has the << operator defined. It isn't necessary to do that, sometimes it can be useful, but it's up to you.

Any approach will involve basically writing each individual data member of your Inventory object to the output stream. You can do that right here within this save function. You wouldn't need to use the this pointer, just refer to each member directly. Without seeing the definition of the Inventory class I cannot be more specific.

Thanks, I think it will be easier to overwrite the operator because of the sturture of my inventory.

My inventory is basically an int _count for the number of items and an array of Town objects
each town object then has a few properties like the name and a spec "specifications" object of the class Townspec
I'll try t do it and write here if I face some difficulties.
Topic archived. No new replies allowed.