- C++ Input/Output Models
- The Stream Inserter Operator <<
- The Stream Extractor Operator >>
- From Here
The Stream Extractor Operator >>
Extractors are functions used to extract or remove data or objects from an input source. The right bit Shift operator (>>) is overloaded to extract data from an input stream and then assigns it to built-in or user-defined datatypes. For user-defined types, the extractor function translates a generic stream of bytes into the object's internal representation or native format. Similar to the inserter, the extractor should maintain the semantics of the operator >>. The extractor is declared as a friend member function. The definition of the friend operator >> function could take this form:
istream& operator>>(istream& In, class_type &class_object) { In >> X; // extract data from stream X_data_member = X; // assign to data member of class In >> Y; // extract more data from stream Y_data_member = Y; // assign to another data member ... return In; }
To create an extractor for a user-defined object, the prototype is listed as part of the declaration for the class:
friend istream& operator>>(istream&,class_type &class_object);
The first parameter in the parameter list is a reference to an istream. The second parameter in the list is a reference to class_object. This object has to be a reference; it's not a const because the object will be altered when data is assigned. The istream appears on the left side of the operator and the class_object appears on the right side of the operator. It returns a reference to the istream to allow numerous extractors to be strung along into one message. It's also a friend operator.
This is the prototype for our extractor of the user-defined class course:
friend istream& operator<<(istream& In,course &Course);
Listing 6 shows the definition for the friend operator >> for the course class:
Listing 6 Defining the friend Operator >> for a User-Defined Object
istream& operator>>(istream &In,course &Course) { string Clause; ... In >> Clause; if(ValidHornClause(Clause)){ Temp = filterClause(Clause); //parse clause and assign data to the appropriate data members } ... return In; }
For the extractor of the course class, a string is extracted from the input stream. The string is formatted as a horn clause of the form described earlier. The function calls a member function that determines whether the horn clause is valid. If so, the horn clause is passed to a filterClause() member function that filters out all special characters except the comma (,), which separates the data that is to be assigned to the course object. The returned string Temp can then be parsed and data assigned to the appropriate data members. This process should be contained in a member function that accepts the horn clause as a string.
Extractors can also be defined that extract course object data from an input stream of HTML or XML tags.