• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Filestream

Im trying to write a simple card game, and I have a BunchOfCards class to represent collections of cards. Im trying to overload the << operator, so that a filestream binded to a formatted text file, will fill that collection with Card objects.

The code I have is for the overloaded operator, below, and the driver program to test it. I checked www.cplusplus.com reference, and it says that ifstream and fstream inherit the getline() method, but i've tried both, and my compiler (Dev-C++) tells me theres no matching function for it.

Can anyone help? Thanks
 
First off you should probably use istream instead of fstream. You're just taking input, and you shouldn't care whether it's a file or a socket or a punch card reader.

And second you should follow the convention used by e.g. cin:

cin >> myint;

myfstream >> mybunchofcards;

instead of:

mybunchofcards << myfstream;

I believe you need to make the operator standalone in order to do that, so instead of having a method operator<<, you'd have a standalone operator>>:

std::istream&amp; operator>> (std::istream&amp; is, BunchOfCards&amp; boc) // return a reference; you don't want to create a copy
{
// take input from 'is', and return is
}

oh, and not *all* operators return *this 😉 (comparison operators return bool, for example)
 
followup question:

i have a ifstream object:

ifstream f;

how would I read just the first line from this file stream into a string variable:

string lineBuffer;

I've tried several different solutions, but none of these have worked (at least on my computer / compiler). These are the two that came the "closest" to working out
😕 :
 
Back
Top