I’m working on a school project to implement a c++ class for polynomials. Something my class is supposed to do is read polynomials from standard in, or from a file. I thought about overloading >> until I read the following on my favorite c++ reference site:
Notice that the istream extraction operations use whitespaces as
separators, therefore this operation will only extract what can be
considered a word from the stream. To extract entire lines of text,
refer to the string overload of global function getline.
This got me all inspired to overload the global function getline for my polynomial class so that it can read whole lines from a file. There are lots of tutorials and articles describing how to overload the stream extraction operator, but I couldn’t find any details about getline. Should I just overload it however I want? From the reference this appears to be how it’s done.
In some of the overloaded getline functions I’ve seen (such as at the bottom of the page linked to), I noticed they return something like “basic_istream”. Is it enough that I just return istream? What about for “char_type”? Would char suffice?
Basically I want to know: is this one of those anything goes overloads, or is there some finicky detail I should be worried about?
This is the header I’ve cooked up:
class Polynomial {
public:
friend istream& getline(istream& is, Polynomial & poly);
friend istream& getline(istream& is, Polynomial & poly, char delim);
};
friend istream& getline(istream& is, Polynomial & poly) {
return getline(is, poly, '\n');
}
friend istream& getline(istream& is, Polynomial & poly, char delim) {
// read enough tokens to make a term
// stop when we get to the delimiter
return is;
}
Thanks!
You should still overload
operator >>. Within your operator implementation, you can extract as many ‘words’ as you need (I’m assuming one per coefficient or so). Don’t try to overloadgetline, thats about getting a line not aPolynomial.